parsley custom validator not responding on First click

190 Views Asked by At

I am trying to do luhn check validation for a field which should be validated after parsley.validate() method.

Please find my below code,

<input type="text" maxlength="19" data-parsley-required="true" data-parsley-length="[13,19]" data-parsley-type="digits" data-parsley-required-message="Enter Credit card number" data-parsley-type-message="Incorrect card number" data-parsley-minlength-message="Incorrect card number" data-parsley-maxlength-message="Incorrect card number" id="creditCardNumber" name="CardNumber" data-parsley-luhn="true" required>

if($("#form").parsley().validate()){ //add the card validator: window.Parsley.addValidator('luhn',{ validateNumber: function (value) { val = value.replace(/[ -]/g, ''); var digit, n, sum, _j, _len1, _ref2; sum = 0; _ref2 = val.split('').reverse(); for (n = _j = 0, _len1 = _ref2.length; _j < _len1; n = ++_j) { digit = _ref2[n]; digit = +digit; if (n % 2) { digit *= 2; if (digit < 10) { sum += digit; } else { sum += digit - 9; } } else { sum += digit; } } if(sum % 10 === 0){ return true; }else{ return false; } } }); }

Validation works only when I click the submit button second time. Any help will be appreciated.

Thanks

1

There are 1 best solutions below

0
On

Call window.Parsley.addValidator once, at init time.

BTW, there's a lunh validator already coded for you