Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

allow only letters and spaces validate 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" the space creates a problem. how can i allow spaces too in my rule?

like image 432
Beb Pratza Ballus Avatar asked Oct 25 '13 14:10

Beb Pratza Ballus


2 Answers

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"); 
like image 67
Rory McCrossan Avatar answered Sep 27 '22 15:09

Rory McCrossan


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
                }
}
        });
like image 38
Sameera Prasad Jayasinghe Avatar answered Sep 27 '22 17:09

Sameera Prasad Jayasinghe