Search code examples
javascriptregexspecial-charactersalphanumeric

regex to strictly check alphanumeric and special character


To check alphanumeric with special characters

var regex = /^[a-zA-Z0-9_$@.]{8,15}$/;
   return regex.test(pass);

But, above regex returns true even I pass following combination

asghlkyudet

78346709tr

jkdg7683786

But, I want that, it must have alphanumeric and special character otherwise it must return false for any case. Ex:

fg56_fg$

Sghdfi@90


Solution

  • You can replace a-zA-Z0-9_ with \w, and using two anchored look-aheads - one for a special and one for a non-special, the briefest way to express it is:

    /^(?=.*[_$@.])(?=.*[^_$@.])[\w$@.]{8,15}$/