Reputation: 221
I have this code:
$(document).ready(function(){
jQuery.validator.addMethod("lettersonly", function(value, element) {
return this.optional(element) || /^[a-z]+$/i.test(value);
}, "Only alphabetical characters");
But if I insert a double name like "Mary Jane" the space creates a problem. how can i allow spaces too in my rule?
Upvotes: 5
Views: 21728
Reputation: 1810
jQuery.validator.addMethod("lettersonly", function(value, element) {
return this.optional(element) || /^[a-z\s]+$/i.test(value);
}, "Only alphabetical characters");
and
$('#yourform').validate({
rules: {
name_field: {
lettersonly: true
}
}
});
Upvotes: 2
Reputation: 383
^\S\n
add this to in between your square brackets
This is a double negative that checks for not-not-whitespace or not-newline.
It will only check for a whitespace, but not a newline. Your test should look like this:
/^[a-z^\S\n]+$/i.test(value)
Source: @Greg Bacon's answer
EDIT: you may want to add A-Z
as well for capital letters
Upvotes: 1
Reputation: 337610
You need to add the whitespace character (\s
) to your Regex:
jQuery.validator.addMethod("lettersonly", function(value, element) {
return this.optional(element) || /^[a-z\s]+$/i.test(value);
}, "Only alphabetical characters");
Upvotes: 8