Back to Top

Add custom js validation rule in Magento2

Updated 23 February 2024

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 :

  1. min_text_length
  2. max_text_length
  3. max-words
  4. min-words
  5. range-words
  6. letters-with-basic-punc
  7. alphanumeric
  8. letters-only
  9. no-whitespace
  10. zip-range
  11. 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.

Searching for an experienced
Magento 2 Company ?
Find out More
. . .

Leave a Comment

Your email address will not be published. Required fields are marked*


Be the first to comment.

Back to Top

Message Sent!

If you have more details or questions, you can reply to the received confirmation email.

Back to Home