1

How to validate a username using php

My rules are:

Username can only contain letters, numbers and 1 underscore.

This is my current preg_match

preg_match('/^[a-zA-Z0-9][_]{1}[a-zA-Z0-9]+$/',$_POST['uname'])
1
  • On at least two of your previous questions, you say "thanks", but didn't accept the answer. Go back over your other questions and, if an answer helped you, click the big check mark next to that answer. Commented Dec 21, 2011 at 16:08

1 Answer 1

2

This should do it:

/^[a-zA-Z0-9]*_?[a-zA-Z0-9]*$/

Keep in mind that a character class of a single item is redundant. Write the atom solely instead. And {1} is another seriously redundant quantifier.

/[_]{1}/

is just the same as

/_/

Edit:

Based on the new constrains and in the helpful comment by chris, this seems to be a better regex:

/^[a-zA-Z0-9]+_?[a-zA-Z0-9]+$/D

It matches usernames of at least two character, not ending or beginning with the optional underscore, and no newlines at the end.

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

5 Comments

Thanks :D But I have another question, I also need that _ should not be first and last of the username myusername - not allowed myusername - not allowed
@user1033600 what's the minimum number of characters allowed?
use the D flag unless you like usernames with a newline as the last character /^[a-zA-Z0-9]*_?[a-zA-Z0-9]*$/D
Sorry @chris I didn't know about this flag. I updated the answer — thanks for pointing it out!
+1. ^[a-zA-Z0-9]+_?[a-zA-Z0-9]+$ does indeed work. However, a more efficient way of writing this would be: ^[a-zA-Z0-9]+(?:_[a-zA-Z0-9]+)?$ This is much more efficient in declaring a non-match when given longish invalid strings such as: "1234567890123456789012345678901234567890123456789#"

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.