Question

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?

Was it helpful?

Solution

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

OTHER TIPS

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

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top