Php expression validation

just a quick question am abit rubish with regex, so I thought I would post it here. The following is a regular expression to validate a username.

  • Must be 4 to 26 characters

  • Start with at least two letters

  • May contain only numbers and one underline and one dot

I still have it, but it doesn’t work

<?php

$username=$_POST['username'];

if (!eregi("^([a-zA-Z][0-9_.]){4,26}$",$username))
{
 return false;
}
else
{
 echo "username ok";
}

?>

Thank:)

+5
source share
3 answers

You can use regex

/^(?=[a-z]{2})(?=.{4,26})(?=[^.]*\.?[^.]*$)(?=[^_]*_?[^_]*$)[\w.]+$/iD

how in

<?php

$username=$_POST['username'];

if (!preg_match('/^(?=[a-z]{2})(?=.{4,26})(?=[^.]*\.?[^.]*$)(?=[^_]*_?[^_]*$)[\w.]+$/iD',
                $username))
{
 return false;
}
else
{
 echo "username ok";
}

?>
  • ^(?=[a-z]{2}) provide the string "Start with at least two letters."
  • (?=.{4,26}) make sure it should be between 4 and 26 characters long.
  • (?=[^.]*\.?[^.]*$)ensures that the following characters contain no more than one .to the end.
  • (?=[^_]*_?[^_]*$) _.
  • [\w.]+$ . , - , _ ..

(: , hello_world .)

+15

, , , , .

function checkUsername($username) {
    $username = trim($username);
    if (empty($username)) {
        return "username was left blank.";
    }elseif (strlen($username) < 4) {
        return "username was too short";
    }elseif (strlen($username) > 26) {
        return "username was too long";
    }elseif (!preg_match('~^[a-z]{2}~i', $username)) {
        return "username must start with two letters";
    }elseif (preg_match('~[^a-z0-9_.]+~i', $username)) {
        return "username contains invalid characters.";
    }elseif (substr_count($username, ".") > 1) {
        return "username may only contain one or less periods.";
    }elseif (substr_count($username, "_") > 1) {
        return "username may only contain one or less underscores.";
    }

    return true;
} 

, , :

$validUsername = checkUsername($username);

if ($validusername !== true) {
     echo "An error occured: " . $validUsername;
}

, , , , , . ereg, , preg_match.

! == , , ( true ). FYI.

+5

The part in which you said:

and one underline and one dot

will keep me away from regular expressions to be honest!

I would do something like:

if(!eregi('^[a-zA-Z]{2}$', substr(0,2))) {
    // .... check for only 2 dots here later ....
}
0
source

All Articles