3

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).

1 Answer 1

6

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'));
});
6
  • ok and where should put this code? JS file, but where is good place for this? If I want to use it in some form I also add only validate-custom-class in the way it is done with other validation classes? Jun 18, 2016 at 12:12
  • Yes same way as it's done with other validation classes. You place the direct JS in a <script> tag below your form or you can put this code in a JS file and include it in your page head tag it's up to you Jun 18, 2016 at 12:21
  • is there any recommended way to add it globally, so any of my form or setup script could use this custom one? Jul 31, 2016 at 17:59
  • @lord_of_strings well if you add that JS on every page you'll be able to use it globally ;) Jul 31, 2016 at 18:40
  • 1
    @lord_of_strings you can follow this link: alanstorm.com/magento_2_javascript_css_layout_woes or look for "add JS globally Magento 2" on StackExchange Jul 31, 2016 at 18:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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