Search code examples
phpregexvalidationconstraintspassword-strength

Validate user-submitted username string for qualifying length and character constraints


The regex below is to validate a username.

  • Must be between 4-26 characters long

  • Start with atleast 2 letters

  • Can only contain numbers and one underscore and one dot

I have this so far, but isn't working.

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

Solution

  • You could use the regex

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

    as in

    <?php
    
    $username=$_POST['username'];
    
    if (!preg_match('/^(?=[a-z]{2})(?=.{4,26})(?=[^.]*\.?[^.]*$)(?=[^_]*_?[^_]*$)[\w.]+$/iD',
                    $username))
    {
     return false;
    }
    else
    {
     echo "username ok";
    }
    
    ?>
    
    • The ^(?=[a-z]{2}) ensure the string "Start with atleast 2 letters".
    • The (?=.{4,26}) ensure it "Must be between 4-26 characters long".
    • The (?=[^.]*\.?[^.]*$) ensures the following characters contains at most one . until the end.
    • Similarly (?=[^_]*_?[^_]*$) ensures at most one _.
    • The [\w.]+$ commits the match. It also ensures only alphanumerics, _ and . will be involved.

    (Note: this regex assumes hello_world is a valid user name.)