Reputation: 27
I've wrote a regex:
/^[a-zA-Z\-\_\. ]{2,60}$/
It does work fine-ish however it allows --- or ___ or ... or even -_. to be entered as an input (without 2 alpha at least) and I don't want that. For instance I can have -aa, a-a, aa--- (similarly for the other characters).
The requirement is that there should be at least 2 alpha in the string, and the hyphens and the other 2 non-alpha symbols mentioned can be anywhere inside the string.
Upvotes: 1
Views: 127
Reputation: 627335
Use
/^(?=(?:[^a-zA-Z]*[a-zA-Z]){2})[-_. a-zA-Z]{2,60}$/
See the regex demo
Details:
^
- start of string(?=(?:[^a-zA-Z]*[a-zA-Z]){2})
- at least 2 alpha chars in the string (that is, there must be exactly 2 consecutive occurrences of:
[^a-zA-Z]*
- zero or more chars other than ASCII letters[a-zA-Z]
- an ASCII letter)[-_. a-zA-Z]{2,60}
- 2 to 60 occurrences of allowed chars$
- end of stringNote you do not need to escape -
if it is at the start/end of the character class. _
is a word char, no need escaping it anywhere. The .
does not need escaping inside a character class.
To tell the regex engine to limit .
, _
and -
chars to max 10 in the string, add (?!(?:[^._-]*[._-]){11})
negative lookahead after ^
anchor:
/^(?!(?:[^._-]*[._-]){11})(?=(?:[^a-zA-Z]*[a-zA-Z]){2})[-_. a-zA-Z]{2,60}$/
Upvotes: 1