Allow only letters and spaces validating jquery

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", space creates a problem. How can I allow spaces in my rule?

+4
source share
3 answers

You need to add a space character ( \s) in Regex:

jQuery.validator.addMethod("lettersonly", function(value, element) {
    return this.optional(element) || /^[a-z\s]+$/i.test(value);
}, "Only alphabetical characters"); 
+7
source

^\S\n

add this between the square brackets

This is a double negative value that checks for non-non-spaces or non-newlines.

It will check only a space , but not a new line. Your test should look like this:

/^[a-z^\S\n]+$/i.test(value)

: @Greg Bacon answer

EDIT: A-Z,

+1
jQuery.validator.addMethod("lettersonly", function(value, element) {
return this.optional(element) || /^[a-z\s]+$/i.test(value);
}, "Only alphabetical characters");

$('#yourform').validate({
            rules: {
                name_field: {
                    lettersonly: true
                }
}
        });
+1

All Articles