开发者

How do I validate a username using php? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.

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 question

How do I validate a username using PHP?

On my registration page I need to validate the usernames.

Acceptable (for example) Only letters, numbers and _ :

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}$/
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜