开发者

Make sure username is not a phone number

I'm writing a mobile website and I would like the user to be able to login via username or phone number. I think the easist way to validate their response it to not allow them to signup using a phone number as their user name.

The problem is that I'll need to check if the input of the username field is JUST a 10 or 11 digit number. This is where my inexperance in regex comes to my disadvantage. I'm hoping to try something like

    function do_reg($text, $regex)
{
    if (preg_match($regex, $text)) {
        return TRUE;
    } 
    else {
        return FALSE;
    }
}

     $username = $_POST['username'];
     if(do_reg($username, '[0-9]{10,11}')){
            die('cannot use a 10 or 11 digit number as a username');
     }

The above regex is matching all numbers that are 10-11 digits long. I think maybe I need a way to say if the ONLY thing in the user input field is a 10-11 digit number get mad otherwise release the butterflies and rainbows.

EDIT: For the record I decided to make sure the username wasn't JUST a number. Thought this would be simpler and I didn't like the idea of having people use numbers as logins.

So I ended up with

i开发者_开发技巧f (!empty($username) && preg_match('/^\d+$/', $username )) {
              die('username cannot be a number');
}

Thanks for the help all.


You are almost correct, except PCRE in PHP requires delimiters, and probably some anchors to make sure the field consists only of numbers.

 if(do_reg($username, '/^\d{10,11}$/')){
//                     ^^         ^^

And probably use \d instead of [0-9].

(BTW, you should just call preg_match directly:

if (!preg_match('/^\d{10,11}$/', $username)) {
   release('bufferflies', 'rainbows');
}


You need to anchor the regex to match the entire string: ^[0-9]{10,11}$.

^ matches the beginning of a string; $ matches the end.


Limit usernames to only 10 characters and require there username to start with a letter. How would a user write a 10 digit phone number as their username if they are required to enter in at least 1 alpha character (since phone numbers can't start with a 0/o or a 1/l)? (Heck I would require at least 3 alpha chars just to be safe).

When your app gets bigger then you can allow for longer usernames and take into account some of these issues:

Do not use ^ or $ signs if you are only testing the username: if(do_reg($username, '/^\d{10,11}$/')){

The reason I say this is anyone could defeat that by placing a letter in their username, a1235551212 instead use this: if(do_reg($username, '/\d{10,11}/')){ because that will flag a1235551212d

Also, importantly, remember, that all of these regular expressions are only checking for numbers, there's nothing to stop a user from doing the following: ltwo3for5six7890. Unless of course you limit the username size.


You just should include start and end of the string in the regex

^[0-9]{10,11}$
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜