JavaScript RegEx to only allow alpha numeric characters and some special characters

In the textarea field, I want to allow only alphanumeric characters, - (hyphen), / (slash) ,. (period) and space. I went through similar questions, but somehow, my exact requirements seem to be different. So, below came a regular expression that I read after reading the answers by members:

/^[a-z0-9\-\/. ]+$/i

I tested the regex and so far it works, but I want to double check. Check if the above regex matches my requirements.

+4
source share
1 answer

You avoid too much

 /^[a-z0-9/. -]+$/i 

In the character class, only [ , ] , \ , - and ^ have a special meaning, ^ even if it is only the first character and - if it is between characters.

To match a literal ^ , just put it in any position except the first. To fit the letter - literally, do not put it between characters (i.e., at the beginning or at the end).

Dump things like / ,. or $ , never required.

+6
source

All Articles