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'])
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'])
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.
D flag unless you like usernames with a newline as the last character /^[a-zA-Z0-9]*_?[a-zA-Z0-9]*$/D^[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#"