allow only letters and spaces validate jquery

Beb Pratza Ballus picture Beb Pratza Ballus · Oct 25, 2013 · Viewed 18.6k times · Source

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?

Answer

Rory McCrossan picture Rory McCrossan · Oct 25, 2013

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");