I need help with my regular expression written in javascript. I have tried using the regularExpression generator online, and the best i can e up with is the this:
^[a-z.-]{0,50}$
The expression must validate the following
- String first char MUST start with a-z (no alpha)
- String can contain any char in range a-z (no alpha), 0-9 and the characters dash "-" and dot "."
- String can be of max length 50 chars
Examples of success strings
- username1
- username.lastname
- username-anotherstring1
- this.is.also.ok
No good strings
- 1badusername
- .verbad
- -bad
- also very bad has spaces
// Thanks
I need help with my regular expression written in javascript. I have tried using the regularExpression generator online, and the best i can e up with is the this:
^[a-z.-]{0,50}$
The expression must validate the following
- String first char MUST start with a-z (no alpha)
- String can contain any char in range a-z (no alpha), 0-9 and the characters dash "-" and dot "."
- String can be of max length 50 chars
Examples of success strings
- username1
- username.lastname
- username-anotherstring1
- this.is.also.ok
No good strings
- 1badusername
- .verbad
- -bad
- also very bad has spaces
// Thanks
Share Improve this question asked Jan 14, 2021 at 12:38 Hans PreutzHans Preutz 6992 gold badges11 silver badges29 bronze badges 03 Answers
Reset to default 4Almost (assuming "no alpha" means no uppercase letters)
https://regex101./r/O9hvLP/3
^[a-z]{1}[a-z0-9\.-]{0,49}$
The {1} is optional, I put it there for descriptive reasons
I think this should cover what you want
^[a-z][a-z0-9.-]{0,49}$
That is starts a-z
but then has 0-49 of a-z
, 0-9
or .-
Live example: https://regexr./5k8eu
Edit: Not sure if you intended to allow upper and lowercase, but if you did both character classes could add A-Z
as well!
If the .
and -
can not be at the end, and there can not be consecutive ones, another option could be:
^[a-z](?=[a-z0-9.-]{0,49}$)[a-z0-9]*(?:[.-][a-z0-9]+)*$
Explanation
^
Start of string[a-z]
Match a single char a-z(?=[a-z0-9.-]{0,49}$)
Assert 0-49 chars to the right to the end of string[a-z0-9]*
Match optional chars a-z0-9(?:[.-][a-z0-9]+)*
Optionally match either.
or-
and 1+ times a char a-z0-9$
End of string
Regex demo