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
1 |
data-validate="{required:true, 'validate-custom-name':true}" |
2) Add js validation for “Validate-custom-name”
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<script type="text/javascript"> 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')); }); </script> |
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. 🙂
if I need to continue my form validation after this, what should be done?
this helped in add custom validation to the product option. thank you for sharing your knowledge.
Where is the js files placed in the file system?