Laurence Schellevisch Laurence Schellevisch - 1 month ago 7
PHP Question

check if username doesnt contain numbers or other weird signs? PHP

i have a username but i want to check if the username doenst contain any numbers or other things that does not belong in a username.

Example:

if ($username !contain "1234567890/.,;'\[]") {
send username to db
} else {
echo 'your username is incorrect';
}


How do i do this?
the username is represents the real name in my code.

Answer

Among the 1000 ways you can do this, one is regular expressions:

if (!preg_match("![0-9/.,;'\\\[\]]!", $username))  {
    //send username to db
} else {
   echo 'your username is incorrect';
}

An alternative is to whitelist permitted characters rather than blacklist invalid ones:

//Allows letters and a single quote (not uncommon in some names)
if (preg_match("!^[A-Za-z']+$!", $username))  { 
    //send username to db
} else {
   echo 'your username is incorrect';
}
Comments