Magento – How to add custom js form validation with custom error message in magento2

form-validationmagento2validation

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

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;
});

and added

validate-testx

to the filed's css class but it did not work. I am using magento 2, please help.

Best Answer

I wanted a to add a custom rule with custom error message, I achieved it using:

<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.