Reputation: 1261
I wanted to validate the Name data files with following condition
So I tried the following Regex
const regExp = /^[a-zA-Z0-9]+[a-zA-Z_-]+[a-zA-Z0-9]$/;
I need at least two characters, remaining are optional in the regExp
everything works fine except this [a-zA-Z0-9]
in the last, I want to make this optional
Upvotes: 1
Views: 99
Reputation: 626927
You may consider using
/^(?=.{2})(?![^a-zA-Z]+$)[a-zA-Z0-9]+(?:[_-][a-zA-Z0-9]+)*$/
See the regex demo
Details
^
- start of string (?=.{2})
- at least two chars(?![^a-zA-Z]+$)
- the string can't have no ASCII letter[a-zA-Z0-9]+
- 1+ ASCII alnum chars(?:[_-][a-zA-Z0-9]+)*
- 0 or more sequences of _
or -
followed with 1+ ASCII alnum chars$
- end of string.Upvotes: 1