There are many predefined js validation rules available in magento2.You just need to add CSS class for that rule to apply.
Some of them are given below :
- min_text_length
- max_text_length
- max-words
- min-words
- range-words
- letters-with-basic-punc
- alphanumeric
- letters-only
- no-whitespace
- zip-range
- integer
and there are many more….
But we can also define our new custom validation rule and override a predefined rule and apply it as CSS class and to do that we need to include validation.js file (located in lib/web/mage directory of Magento2) in our module js file.
require([ 'jquery', 'mage/validation' ], function($){ $.validator.addMethod( 'integer', function (value, element) { return this.optional(element) || /^-?\d+$/.test(value); }, $.mage.__('A positive non-decimal number please')); $.validator.addMethod( 'validate-script-tags', function (value, element) { return !/<script\b[^>]*>([\s\S]*?)<\/script>/.test(value); }, $.mage.__('SCRIPT tags are not allowed.')); });
Here I have override integer rule message which was previously “A positive or negative non-decimal number please” but after override it becomes “A positive non-decimal number please” and describe a new rule validate-script-tags which will validate the use of script tags in form input fields Now we can use these two classes to validate via from form or js file.
Be the first to comment.