How do I validate a username using php? [closed]
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this questionHow do I validate a username using PHP?
On my registration page I need to validate the usernames.
Acceptable (for example) Only letters, numbers and _ :
- anas fares
- anasfares 开发者_开发百科
- AnAsFaReS
- anas45 fares
- 35fares arty
- anas_fares
Unacceptable (for example) :
- anas.fares
- anas #fares
- 57fares
- @^*12sf
- anas-fares
Use a regular expression to restrict the characters which a string may contain. In PHP, preg_match
will return 0 if the pattern isn't matched, non-zero otherwise:
if (!preg_match('/^[ \w]+$/', $username)) {
$error = "Invalid username";
}
You should also enforce a minimum/maximum length with either strlen
or a modified regular expression. This one only matches strings from two to ten characters in length:
/^[ \w]{2,10}$/
精彩评论