AJAX form submit with default magento 2 form validation

AJAX form submit with default magento 2 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 magento 2 form validation 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.

require(['jquery','mage/validation'], function($){
var dataForm = $('#form-validate');
dataForm.mage('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

require(['jquery','mage/validation'], function($){
var dataForm = $('#form-validate');
dataForm.mage('validation', {});
$('button#submit-button').click( function() { //can be replaced with any event
var status = dataForm.validation('isValid'); //validates form and returns boolean
if(status){
console.log('form is validated'); //form is valid
//Do the AJAX call here
}else{
console.log('form is not validated');
}
});
});

 

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

I hope above helps. Happy coding!!

Check out my other blog posts related to magento and shopify here.