AJAX form submit with magento2 default form Validation

AJAX form submit with magento2 default form Validation

Hey guys,

I have returned back to you with another simple yet used in day to day magento 2 development task i.e submitting the forms using AJAX with default magento 2 form validation.

Actually achieving both individually i.e either normal AJAX form submission or using default form validation provided by magento2 is quite easy. You can refer validating a custom form in Magento2, to see how validation works in magento2. But there are many times down the road, you may need to use both the magento form validation (because it is really great!!) and AJAX form submission(because it looks great!!) at the same time. You may have faced some difficulties in achieving above and I too didn’t found much solution over internet, so I thought sharing one.

So, Let’s begin!!

On the bottom of your template file where you have added your form element, you may have added some codes like below for validation.

This will validate your form with form id “form-validate”. Now on the submit button click you need to check if the form is valid and then only you can do an AJAX call. So for that

 

The main thing in above code snippet is checking if the form is valid or not.

I hope above helps. Happy coding!!