Js Regular expression for first name

8.7k Views Asked by At

I am looking for a regular expression which fulfil below conditions

  • Min 1 and Max 50 char
  • No spaces at the beginning and ending of string
  • Allow only one space, dot between 2 words.

I am using below expression which causes catastrophic backtracking issue. Expression -

/^[a-zA-Z]+(?:(?:|['_\. ])([a-zA-Z]*(\.\s)?[a-zA-Z])+)*$/

How can I prevent this issue?

1

There are 1 best solutions below

0
On

You may use

/^(?=.{1,50}$)[a-z]+(?:['_.\s][a-z]+)*$/i

See the regex demo.

Details

  • ^ - start of string
  • (?=.{1,50}$) - there must be 1 to 50 chars in the string
  • [a-z]+ - 1 or more ASCII letters
  • (?:['_.\s][a-z]+)* - 0 or more sequences of
    • ['_.\s] - a ', _, . or whitespace
    • [a-z]+ - 1 or more ASCII letters
  • $ - end of string
  • /i - a case insensitive modifier.