Magento 2 Form Validation – Accessing mage/validation/validation.js Return Values

form-validationjavascriptjqueryknockoutjsmagento2

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);
    }
}

Best Answer

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.