I am working on writing a PHP login system. I have everything that I need working, but I would like to verify that a username entered during the registration only contains alphanumeric characters. So how could I take a variable, say $username, and ensure that it contained only alphanumeric characters?
preg_match("#[a-z]+#",$password)) { $passwordErr = "Your Password Must Contain At Least 1 Lowercase Letter!"; } else { $cpasswordErr = "Please Check You've Entered Or Confirmed Your Password!"; } } //Validates firstname if (empty($_POST["firstname"])) { $firstErr = "You Forgot to Enter Your First Name!"; } else { $ ...
Validate Form Data With PHP The code is now safe to be displayed on a page or inside an e-mail. We will also do two more things when the user submits the form: Strip unnecessary characters (extra space, tab, newline) from the user input data (with the PHP trim() function)
Form Validation is a necessary process before the data entered in the form is submitted to the database. This is done to avoid unnecessary errors. In PHP Form validation, the script checks for data in respective fields based on the rules set by the developer, and returns an error if it does not meet the requirements.
if(preg_match('/^\w{5,}$/', $username)) { // \w equals "[0-9A-Za-z_]"
// valid username, alphanumeric & longer than or equals 5 chars
}
OR
if(preg_match('/^[a-zA-Z0-9]{5,}$/', $username)) { // for english chars + numbers only
// valid username, alphanumeric & longer than or equals 5 chars
}
The Best way I recommend is this :-
$str = "";
function validate_username($str)
{
$allowed = array(".", "-", "_"); // you can add here more value, you want to allow.
if(ctype_alnum(str_replace($allowed, '', $str ))) {
return $str;
} else {
$str = "Invalid Username";
return $str;
}
}
If you don't care about the length, you can use:
if (ctype_alnum($username)) {
// Username is valid
}
http://www.php.net/manual/en/function.ctype-alnum.php
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With