I am trying to create a regex pattern for name validation. Application name must have the following:
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.
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 inputYou 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