Magento – M2: Custom form validation

form-validationjavascriptmagento-2.1magento2

I have an ajax form I need to call before allowing user to continue to add a product to cart. I have the form popping up but I also need to validate the contents before it submits. However the validation has changed from M1 to M2.

Essentially I need to:

  • on form submit
  • validate the form
  • if validate then submit AJAX request
  • if not valid then show validation errors.

How do I catch the form submit after the validation has happened? As if I use a regular JS event then the validation hasn't happened yet

Hope that makes sense.

Best Answer

Use below code for submit and validate form using ajax

require([
    'jquery',
    'mage/mage',
    'Magento_Catalog/product/view/validation',
    'Magento_Catalog/js/catalog-add-to-cart'

], function ($) {
    'use strict';

    $('#custom_addtocart_form').mage('validation', {
        radioCheckboxClosest: '.nested',
        submitHandler: function (form) {
            jQuery.ajax({
                url: form.action,
                type: 'POST',
                dataType: 'json',
                data: form.serialize(),
                showLoader: true
            }).done(function (data) {
                return true;
            });

        }
    });


});