0

This is my first go at a Magento 2, so please bear with me. I want to add functionality that scrolls the page to an error message if a form does not pass validation. Currently, I am listening for a submit event on the #product_addtocart_form and running a checkError function that runs a copy of the grouped product validation code found in mage/validation/validation.js:

function checkError() {
    /* grouped qty validation code taken from mage/validation.js */
    var result = false;
    var total = 0;
    $('#product_addtocart_form').find('input[data-validate*="validate-grouped-qty"]').each(function (i, e) {
        var val = $(e).val();
        if (val && val.length > 0) {
            result = true;
            var valInt = parseInt(val, 10) || 0;
            if (valInt >= 0) {
                total += valInt;
            } else {
                result = false;
                return result;
            }
        }
    });
    if(!(result && total > 0)) {
        $('html, body').animate({
            scrollTop: $('#product_addtocart_form').offset().top
        }, 1000);
    }
}

Obviously, this is not optimal because the validation code is being run twice for every form submit, once in validation.js and once in my code. And because code duplication, etc.

What I would like to know is, is there a way to access the return value of the 'validate-grouped-qty' function in mage/validation/validation.js?

In Magento 1, this could by accomplished by something like the following:

productAddToCartForm.validator.options.onFormValidate = function(result, form) {
    if(!result) {
        $('html, body').animate({
            scrollTop: $('#product_addtocart_form').offset().top
        }, 1000);
    }
}
2

While I did not find exactly what I was looking for (an analog of onFormValidate), I did find out that you can get an 'isValid' boolean return by simply doing:

var isValid = $('#product_addtocart_form').validation('isValid');

If you do not specify 'isValid' as a parameter, validation() will not return a value but instead only validate the form.

For my purposes, this works very well as it accounts for all possible form invalidations - not just the grouped product qty that I specified above.

  • 1
    You can also do $('#product_addtocart_form').valid(). – thdoan May 2 '17 at 10:48
  • And possibly even $('#product_addtocart_form').mage('validation', {}); Haven't tested that one or it's inline counterpart though – Steve Karwacki May 5 '17 at 22:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.