Reputation: 443
I am trying to make a regex to validate a text field in javascript. The condition is that it can contain Characters from a to z (small letters or caps), can include numbers and spaces and the some special characters e.g ()[]’“/.-_&–
It cannot start with a space or end with a space.
I have written the following
([A-Za-z0-9\s*\(\)\[\]'"/.\-_&–])
But I am pretty sure it can be improved upon a lot. Can someone help
Upvotes: 1
Views: 359
Reputation: 784958
You may use this regex:
/^(?! )(?!.* $)[\w *()\[\]'"\/.&–-]+$/gm
Details:
^
: Start(?! )
: Negative lookahead to assert that we don't have a space at start(?!.* $)
: Negative lookahead to assert that we don't have a space at end[\w *()\[\]'"\/.&-]+
: Match 1+ of the allowed characters$
: EndNote that \w
is same as [a-zA-Z0-9_]
Upvotes: 0
Reputation: 1471
^[^\s][\w\s\(\)\[\]\'\"\/\.\-\&\–]+[^\s]$
^
- start[^\s]
- no white space[\w\s\(\)\[\]\'\"\/\.\-\&\–]+
- at least one of those characters (\w means [a-zA-Z0-9_])[^\s]
- no white space$
- endUpvotes: 2