4

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?

8
  • I tried your code and it works fine for me. Commented May 30, 2013 at 15:08
  • How is $my_name being set? ie index.php?name=bob&x gives name as bob. You may want to add a minimum length ie /^[a-zA-Z0-9\._\-]{5,}$/ for string of 5 chars or more Commented May 30, 2013 at 15:11
  • Sorry I forgot to mention that I call this php regex by an ajax post on a keyup event of the input type username field. I don't know if this is an additional valuable info for you. Commented May 30, 2013 at 15:12
  • Why not just exclude the & and + altogether, or do a preg_replace? It's an option. Commented May 30, 2013 at 15:28
  • Yes it's an option, I tried already to replace the & and + with '' but this a very bad UX. I can't give an error message back to my user of what is doing wrong... in order to fix it and proceed. Commented May 30, 2013 at 15:30

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

3 Comments

+1 thought that too (see comment) but it doesn't explain the + (space) as it is not in the regex
Didn't work, as I mention before there is no url request, I use ajax post, I just pass the username as string, so I think there is no need for encodeURI(), please correct me if I'm wrong.
I solved it but I still need an explanation, I will appreciate it if you or someone else can give me. The problem was on the ajax post data. I had this line before to post the username, this worked for a months: data: 'my_name='+ my_name Now I changed it to: data: { my_name: my_name} and it's working. Can anyone explain me why the & and + cause this issue when I use this: data: 'my_name='+ my_name instead of data: { my_name: my_name}
-1
if (!preg_match('/^[a-zA-Z0-9\.\_-]+$/',urldecode($my_name))) {  echo 'no_valid'; }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.