cancel
Showing results for 
Search instead for 
Did you mean: 

How to add custom js form validation in magento2 ?

SOLVED

How to add custom js form validation in magento2 ?

I am trying to do a custom js validation for a form field, I added this in my phtml file :

<script type="text/javascript">

//<![CDATA[
var theForm = new VarienForm('form-validate', true);
Validation.add('validate-testx','You failed to enter baz!',function(v){

if(v == 'baz')
{
return true;
}
return false;
});
//]]>
</script>

 

and added "validate-testx" to the field's css class but it did not work. I am using magento 2, please help.

1 ACCEPTED SOLUTION

Accepted Solutions

Re: How to add custom js form validation in magento2 ?

I achieved it using the following:

<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-member-card', function (value) {

return (value.length === 16 && /^[a-zA-Z0-9]+$/.test(value)); // Validation logic here
}, $.mage.__('Not a valid Membership ID'));

});
</script>

Worked fine.. 

View solution in original post

2 REPLIES 2

Re: How to add custom js form validation in magento2 ?

I achieved it using the following:

<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-member-card', function (value) {

return (value.length === 16 && /^[a-zA-Z0-9]+$/.test(value)); // Validation logic here
}, $.mage.__('Not a valid Membership ID'));

});
</script>

Worked fine.. 

Re: How to add custom js form validation in magento2 ?

Where do we need to put this js file?