Skip to content

Regex for String in React

How shall we write a regular expression to validate a string which should have a length of minimum 1 character and maximum 50 characters, can have both upper case and lower case, alphanumeric, can include space and also have mostly used special characters like @,._-&$#. The first character should be either alphabet or number then rest can be as mentioned above.

*If it is only one character then it should be a alphanumeric one

I have tried a regex with my limited knowledge which looks like

^[a-zA-z]*[a-zA-Zd-_@&$%#s]{1,50}$

But i am not able to match the string if there is only one character given, can anyone guide me to fix this

Answer

You can use

/^(?=[p{L}0-9])[p{L}p{N}_@,.&$%#s-]{1,50}$/u

See the regex demo

Details

  • ^ – start of string
  • (?=[p{L}0-9]) – the first char must be a Unicode letter (p{L}) or an ASCII digit
  • [p{L}p{N}_@,.&$%#s-]{1,50} – one to fifty
    • p{L} – any Unicode letter
    • p{N} – any Unicode digit
    • _@,.&$%#- – any of these chars
    • s – any whitespace
  • $ – end of string.