Adding Custom Global JavaScript Validation in Magento 2

form-validationjavascriptmagento-2.0.5magento2validation

I have done some digging in internet but I haven't found any confirmed solution. What is the way to add custom js validation rule, that can be used globally as for example frontend_class for attributes or validation classes for form's inputs? It would be the best if I could store it in one of my modules.

By the way, for version 2.05 is there any class validating by min or max lenght of string/number of characters? The ones I have found in net don't work (seems to me they are outdated).

Best Answer

Assuming you add a validation class via the frontend_class let's say "validate-custom-class" you'll need to use the following JS to add a custom validation based on a this class:

require([
    'jquery',
    'jquery/ui',
    'jquery/validate',
    'mage/translate'
], function($){ 
    $.validator.addMethod(
        'validate-custom-class', function (value) { 
        // Add your validation logic here
        // Needs to return true if validation pass
        // Or false if validation fails
    }, $.mage.__('Field is not valid'));
});
Related Topic