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
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'));
});
-
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-classin the way it is done with other validation classes?Bartosz Kubicki– Bartosz Kubicki2016年06月18日 12:12:24 +00:00Commented 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 youRaphael at Digital Pianism– Raphael at Digital Pianism2016年06月18日 12:21:56 +00:00Commented 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?Bartosz Kubicki– Bartosz Kubicki2016年07月31日 17:59:20 +00:00Commented 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 ;)Raphael at Digital Pianism– Raphael at Digital Pianism2016年07月31日 18:40:27 +00:00Commented 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 StackExchangeRaphael at Digital Pianism– Raphael at Digital Pianism2016年07月31日 18:52:26 +00:00Commented Jul 31, 2016 at 18:52
Explore related questions
See similar questions with these tags.