Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP regex ampersand issue

I use the following regex to validate a username (input type text in a registration form) in order to make sure that the username contains ONLY alphanumeric characters, dot, dash or underscore.

if (!preg_match('/^[a-zA-Z0-9\.\_-]+$/',$my_name)) {  echo 'no_valid'; }

When I type in the text field for instance % or # or @ I get back correctly the error message that it's not a valid username, also the valid characters (.-_) are accepted, so it seems to work fine until the time I type & or +, then I can type any invalid character that I have already exclude before by using the preg_match.

Could anyone tell me why is this happening and how can I overcome this issue?

like image 346
AlexCode Avatar asked Sep 11 '25 11:09

AlexCode


1 Answers

Problem is somewhere else. Your expression is correct. I tested with PHP. Since it happens with '&' character my guess would be that your data is not converted to URL safe characters before send. Try using encodeURI() function in JS.

like image 170
Bence Gacsályi Avatar answered Sep 13 '25 02:09

Bence Gacsályi