Allow only letters and spaces - jquery validation plugin

Go To StackoverFlow.com

0

I am validating a text field to allow only letters and spaces.

This is the method I am using:

jQuery.validator.addMethod("lettersonly", function(value, element) { 
    return this.optional(element) || /^[a-z]+$/i.test(value);
}, "Please enter only letters"); 

But the regular expression is not allowing spaces between words.

I tried : /^[a-z ]+$/i.test(value) and /^[a-z\s]+$/i.test(value)

jQuery version - 1.7.1

2012-04-04 17:58
by user1313360


9

The regular expression is:

^[a-z\s]*$

LIVE DEMO

2012-04-04 18:01
by gdoron
do you need the | when they are in a character class? i thought that was the point of the character class - jbabey 2012-04-04 18:24
@jbabey. You're right, didn't notice! fixed, thanks - gdoron 2012-04-04 18:27
A problem with expressions like this is that [] classes not necessarily imply that all characters are actually used. For example, the above will accept a string consisting of 100 newlines. I'm not sure this is what OP really meant - georg 2012-04-04 18:49
@thg435. Though you're right, this is was the OP really asked for... : - gdoron 2012-04-04 19:04


0

jQuery.validator.addMethod("lettersonly", function(value, element) { 
    return this.optional(element) || /^[a-zA-Z\s]*$/.test(value);
},"Please enter only letters");

replace this : /^[a-z\s]+$/i

by this :/^[a-zA-Z\s]*$/

I checked It works.

2015-03-18 13:01
by kishor10d
Ads