allow only letters and spaces validate jquery
19,517
Solution 1
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");
Solution 2
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
}
}
});
Solution 3
^\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
![Beb Pratza Ballus](https://i.stack.imgur.com/QmhW7.jpg?s=256&g=1)
Author by
Beb Pratza Ballus
Updated on June 11, 2022Comments
-
Beb Pratza Ballus about 2 years
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?