MagMagento 2: Add new Custom Form Validation

 

FacebookTwitterGoogle+LinkedInPartager
In Magento 1, There was one file validation.js. We can add the new validation on that file or also add in our extension .phtml or .js file.

In Magento 2, We can add our custom validation in .phtml file. It is very good news for us Magento 2 is not using prototype.js. They are using jquery so we can use jquery validation in Magento 2. But there is some different structure to use validation.

Let’s see how we can do this.

1) In input or select tag add our validaion with this code
data-validate=”{required:true, ‘validate-custom-name’:true}”
1
data-validate=”{required:true, ‘validate-custom-name’:true}”

2) Add js validation for “Validate-custom-name”

require([
‘jquery’, // jquery Library
‘jquery/ui’, // Jquery UI Library
‘jquery/validate’, // Jquery Validation Library
‘mage/translate’ // Magento text translate (Validation message translte as per language)
], function($){
$.validator.addMethod(
‘validate-custom-name’, function (value) {
return (value !== ‘test’); // Validation logic here
}, $.mage.__(‘Enter Valid name’));

});

require([
‘jquery’, // jquery Library
‘jquery/ui’, // Jquery UI Library
‘jquery/validate’, // Jquery Validation Library
‘mage/translate’ // Magento text translate (Validation message translte as per language)
], function($){
$.validator.addMethod(
‘validate-custom-name’, function (value) {
return (value !== ‘test’); // Validation logic here
}, $.mage.__(‘Enter Valid name’));

});

Now, When we enter the “test” in text box and click on form submit. They return the error “Enter Valid name”.

So Now Our validaion is working
Best of Luck to create new Validation. 🙂

Leave a Comment