I'm using the validate plugin from http://bassistance.de/jquery-plugins/jquery-plugin-validation/
What i'm trying to find is a way to make some of my form fields accept letters only, no numbers, special chars etc...
Any idea people ? Thanks a lot.
I'm using the validate plugin from http://bassistance.de/jquery-plugins/jquery-plugin-validation/
What i'm trying to find is a way to make some of my form fields accept letters only, no numbers, special chars etc...
Any idea people ? Thanks a lot.
Use below code in your script. this will add a new clause to your validator.
$.validator.addMethod(
"alphabetsOnly",
function(value, element, regexp) {
var re = new RegExp(regexp);
return this.optional(element) || re.test(value);
},
"Please check your input values again!!!."
);
$("#formElement").rules("add", {alphabetsOnly: "^[a-zA-Z'.\\s]$" })
Try This : ( This is perfect custom validation using jquery validator )
$(function() {
$.validator.addMethod("alphabetsnspace", function(value, element) {
return this.optional(element) || /^[a-zA-Z ]*$/.test(value);
});
$("#add-employee").validate({
rules: {
employee_surname: {
required: true,
alphabetsnspace: true
},
employee_firstname: {
required: true,
alphabetsnspace: true
},
employee_othername: {
alphabetsnspace: true
},
father_name: {
required: true,
alphabetsnspace: true
},
mother_name: {
required: true,
alphabetsnspace: true
},
spouse_name: {
alphabetsnspace: true
},
ssn: {
number: true,
},
phone_no: {
number: true,
},
phone_no2: {
number: true,
},
passport: {
number: true,
},
driving_license: {
number: true,
},
email: {
email: true
}
},
messages:
{
"employee_surname":{
alphabetsnspace: "Please Enter Only Letters"
},
"employee_firstname":{
alphabetsnspace: "Please Enter Only Letters"
},
"employee_othername":{
alphabetsnspace: "Please Enter Only Letters"
},
"father_name":{
alphabetsnspace: "Please Enter Only Letters"
},
"mother_name":{
alphabetsnspace: "Please Enter Only Letters"
},
"spouse_name":{
alphabetsnspace: "Please Enter Only Letters"
},
}
});
});
The following method to add a custom validator works fine, But the validation happens on keyup, So the error keeps on popping up while the user is typing the text.
return value.match(new RegExp(""));
The below method works fine for Alphabets and Spaces, Ideal for name fields.
jQuery.validator.addMethod("alphabetsAndSpacesOnly", function (value, element) { return this.optional(element) || /^[a-zA-Z\s]+$/.test(value); }); $("FieldId").rules("add", { alphabetsAndSpacesOnly: true, messages: { alphabetsAndSpacesOnly: "Please enter a valid name." } });
The jQuery Validate plugin already has a rule called lettersonly as part of the additional-methods.js file, which looks like this...
$.validator.addMethod( "lettersonly", function( value, element ) {
return this.optional( element ) || /^[a-z]+$/i.test( value );
}, "Letters only please" );