Reputation: 691
I'm trying to validate the string to have only the followings
1. Numbers (0-9) are valid 2. Letters (A-Z, a-z) are valid 3. No leading spaces are allowed 4. No trailing spaces are allowed 5. A space can be entered in the field text (outside of leading or trailing spaces) 6. The following special characters are allowed: 1. Underscore (_) 2. Hyphen (-) 3. Comma (,) 4. Dot (.)
The following is working for me, except spaces
/^[A-Za-z0-9][A-Za-z0-9\_\.\-\,\s]*$/g
How to avoid leading spaces and trailing spaces with same Regex pattern?
Upvotes: 2
Views: 3343
Reputation: 18611
The leading spaces can be forbidden with (?!\s)
lookahead.
The trailing spaces can be forbidden with (?!.*\s$)
lookahead.
Combine them into your pattern after ^
:
/^(?!\s)(?!.*\s$)[A-Za-z0-9][A-Za-z0-9\_\.\-\,\s]*$/
See proof
Upvotes: 1
Reputation: 163207
If there can be consecutive whitespaces characters in between, you could use an optional part where there second character class is repeated 0+ times ending with the same character class excluding \s
^[A-Za-z0-9](?:[A-Za-z0-9_.,\s-]*[A-Za-z0-9_.,-])?$
Or using \w
to match word characters:
^[A-Za-z0-9](?:[\w.,\s-]*[\w.,-])?$
Note that \s
could also possibly match a newline.
Upvotes: 4