amoralesu
amoralesu

Reputation: 53

Regular expression in javascript to match only letters or spaces

I have the following expression to validate a "name":

/^([a-z\s?]{4,120})[^\s]$/i

But I do not know why accepts special characters: Alex@ is a valid match.

It should be invalid because I have not specified that contains special characters.

Upvotes: 3

Views: 79

Answers (1)

brandonscript
brandonscript

Reputation: 73044

What you want is a minimum of 4 characters - you're trying to get it to work with is expecting at least 5 characters because of the non-optional [^\s] character at the end. Moreover, [^\s] will actually match any character that isn't a space - I'd bet you want to restrict that to being just letters as well?

Try this instead:

^[a-z\s?]{3,119}[a-z]$

Upvotes: 1

Related Questions