Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php code to validate alphanumeric string

I want to validate alphanumeric string in form text box in php. It can contain numbers and special characters like '.' and '-' but the string should not contain only numbers and special characters. Please help with the code.

like image 408
jayant kumar Avatar asked Apr 10 '13 08:04

jayant kumar


People also ask

What is alpha numeric numbers?

Alphanumeric, also referred to as alphameric, is a term that encompasses all of the letters and numerals in a given language set. In layouts designed for English language users, alphanumeric characters are those comprised of the combined set of the 26 alphabetic characters, A to Z, and the 10 Arabic numerals, 0 to 9.

How do you know if a variable is alphanumeric?

An alphanumeric string is a string that contains only alphabets from a-z, A-Z and some numbers from 0-9. Explanation: This string contains all the alphabets from a-z, A-Z, and the number from 0-9. Therefore, it is an alphanumeric string.


2 Answers

Use ctype_alnum like below:

if(ctype_alnum($string)){
    echo "Yes, It's an alphanumeric string/text";
}
else{
    echo "No, It's not an alphanumeric string/text";
}

Read function specification on php.net

like image 101
Ravinder Payal Avatar answered Oct 09 '22 22:10

Ravinder Payal


Try this

// Validate alphanumeric
if (preg_match('/^[a-zA-Z]+[a-zA-Z0-9._]+$/', $input)) {
    // Valid
} else {
    // Invalid
}
like image 45
Sankar V Avatar answered Oct 09 '22 20:10

Sankar V