5

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?

TN888
  • 7,463
  • 9
  • 45
  • 83
Beb Pratza Ballus
  • 221
  • 1
  • 4
  • 14

3 Answers3

8

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"); 
Rory McCrossan
  • 319,460
  • 37
  • 290
  • 318
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
                }
}
        });
1

^\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

Community
  • 1
  • 1
char1es
  • 373
  • 3
  • 18