Use addMethod in jQuery Validate plugin
This is my solution including Greek characters.
$.validator.addMethod('alphabet', function (value, element) {
let regExName = /^[A-Za-zΑ-Ωα-ωίϊΐόάέύϋΰήώ]+$/;
return (regExName.test(value));
}, 'There are non alphabetic characters!');
$("#orderForm").validate({
rules: {
first_name: {
required: true,
alphabet: true
}
});
There are three different issues as outlined by the progressing edits below.
1)
You missed a comma just between selectnic
and the function(
.
Also, try this format instead when using regex
...
jQuery.validator.addMethod("selectnic", function(value, element){
if (/^[0-9]{9}[vVxX]$/.test(value)) {
return false; // FAIL validation when REGEX matches
} else {
return true; // PASS validation otherwise
};
}, "wrong nic number");
EDIT: This answer assumes your original regex
and logic are both correct. Your logic returns false
when the regex
is a match. false
means that validation failed and you will see the error message.
2) EDIT 2:
After creating new methods, you also have to use them. I do not see the selectnic
rule/method used anyplace in your code.
Example:
rules: {
myFieldName: {
// other rules,
selectnic: true // <- declare the rule someplace!
}
}
3) EDIT 3:
And finally, the OP's original true/false
logic was backwards. He wanted to PASS validation upon a regex match… therefore, needs to return true
.
if (/^[0-9]{9}[vVxX]$/.test(value)) {
return true; // PASS validation when REGEX matches
} else {
return false; // FAIL validation
};
DEMO: http://jsfiddle.net/DzvNr/