Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Js Regular expression for first name

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?

like image 538
Rashmi Narware Avatar asked Sep 02 '25 02:09

Rashmi Narware


1 Answers

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.
like image 112
Wiktor Stribiżew Avatar answered Sep 04 '25 15:09

Wiktor Stribiżew