Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP username validation

Tags:

php

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?

like image 303
Adam Thompson Avatar asked Dec 08 '10 03:12

Adam Thompson


People also ask

How to validate password in PHP?

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 { $ ...

Does PHP support validation?

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)

What is PHP form validation?

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.


3 Answers

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
}
like image 120
Ish Avatar answered Oct 01 '22 01:10

Ish


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;
    }
}
like image 29
ifreelancer.asia Avatar answered Oct 01 '22 03:10

ifreelancer.asia


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

like image 33
Matthew Mucklo Avatar answered Oct 01 '22 01:10

Matthew Mucklo