Home > Net >  Improve JS Regex pattern for name validation
Improve JS Regex pattern for name validation

Time:08-26

I am trying to create a regex pattern for name validation. Application name must have the following:

  1. Lowercase alphanumeric characters can be specified
  2. Name must start with an alphabetic character and can end with alphanumeric character
  3. Hyphen '-' is allowed but not as the first or last character e.g abc123, abc, abcd-1232

This is what I got [^\[a-z\] (\[a-z0-9\-\])*\[a-z0-9\]$][1] it doesn't work perfectly. The validation fails if you enter a single character in the field. How can I improve this pattern? Thank you in advance.

CodePudding user response:

You may use the following pattern:

^[a-z](?:[a-z0-9-]*[a-z0-9])?$

Explanation:

  • ^[a-z] starts with lowercase alpha
  • (?: turn off capture group
    • [a-z0-9-]* zero or more alphanumeric OR dash
    • [a-z0-9] mandatory end in alphanumeric only, if length > 1
  • )? make this group optional
  • $ end of input

CodePudding user response:

You are using a negated character class [^ that matches 1 character, not being any of the specified characters in the character class.

That is followed by another character class [1] which can only match 1, so the pattern matches 2 characters, like for example #1


In your examples you seem to have only a single hyphen, so if there can not be consecutive hyphens --

^[a-z][a-z0-9]*(?:-[a-z0-9] )*$

Explanation

  • ^ Start of string
  • [a-z] Match a single char a-z
  • [a-z0-9]* Optionally repeat any of a-z or 0-9
  • (?:-[a-z0-9] )* Optionally repeat matching - followed by at least 1 or a-z or 0-9 (So there can not be a hyphen at the end)
  • $ End of string

Regex demo

  • Related