Maged Saeed
Maged Saeed

Reputation: 1885

name validation with regular expression

I am trying to validate a name field in javascript with the following rules:

I have tried the following regular expression but I want to make sure whether it is correct or not. re = /^[a-z][a-z\s]{3,14}[a-z]$/i;

Upvotes: 1

Views: 91

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626689

You can use

/^(?=.{5,15}$)[a-z]+(?:\s+[a-z]+)*$/i

See the regex demo.

Details

  • ^ - start of string
  • (?=.{5,15}$) - a positive lookahead that only checks if, from the start of string, and up to the end of string, there are any 5 to 15 chars other than line break chars (this is a non-consuming pattern, the regex index is at the start of the string when the pattern is matched)
  • [a-z]+ - (start of the consuming pattern) 1 or more ASCII letters
  • (?:\s+[a-z]+)* - 0+ repetitions of
    • \s+ - 1 or more whitespaces
    • [a-z]+ - 1+ ASCII letters
  • $ - end of string.

JS demo:

var rx = /^(?=.{5,15}$)[a-z]+(?: +[a-z]+)*$/i;
var strs = ["abcde abcde abc","abcde abcde","abcde abcdeabcde","abcde abcd1","abcdeabcde"];
for (var s of strs) {
  console.log(s,"=>",rx.test(s));
}

Upvotes: 1

Related Questions