phpregexvalidationpreg-match

Validate that an input string contains only letters, numbers and underscores


I have this PHP preg_match code that's suppose to only allow a-z (Capital and lowercase) 0-9 and underscores

But when I try signing up with the username "Rizon" it says: Only valid characters are allowed.

Here's the code:

if (!preg_match("[a-zA-Z0-9]_", $_POST['username'])) {
    $_SESSION['error']['username'] = "Only valid characters are allowed."; 
}

How can I fix the preg_match so it will allow usernames such as "Rizon" and usernames with uppercase and/or lowercase letters and/or numbers and/or underscores?


Solution

  • This should do the trick (you need to also check that username only contains your pattern)

     if (!preg_match("/^[a-zA-Z0-9_]+$/",$_POST['username']))
    

    Without adding ^ (start match) and $ (end match) your regular expression will only validate if a pattern is included.