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.
6
-
2what exactly should your validation result be and what did you try?user1914292– user19142922013-04-10 08:11:49 +00:00Commented Apr 10, 2013 at 8:11
-
Show us some valid and invalid inputsSankar V– Sankar V2013-04-10 08:16:32 +00:00Commented Apr 10, 2013 at 8:16
-
it is basically a "asset_details" input box in form. It can accept alphanumeric value along with "." and "-". If user will input only numbers or only "." or "-" then it should give an alert saying that not a valid input type. In short it should accept combination of alphanumeric and "." or "-"jayant kumar– jayant kumar2013-04-10 08:16:41 +00:00Commented Apr 10, 2013 at 8:16
-
For example, jay123: valid 1234:invalid ....: invalid jay.kum:validjayant kumar– jayant kumar2013-04-10 08:20:00 +00:00Commented Apr 10, 2013 at 8:20
-
@jayantkumar did my answer meets your need?Sankar V– Sankar V2013-04-10 10:53:39 +00:00Commented Apr 10, 2013 at 10:53
|
Show 1 more comment
4 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
1 Comment
Christian Hur
Just want to clarify that the "ctype_alnum()" function only checks if a string contains all characters, all numbers, OR both. It won't work if you want to include only characters AND numbers as originally requested.
Try this
// Validate alphanumeric
if (preg_match('/^[a-zA-Z]+[a-zA-Z0-9._]+$/', $input)) {
// Valid
} else {
// Invalid
}
1 Comment
Kamlesh
This solution is not working on Turkish language characters. Thank you
Code:
if(preg_match('/[^a-z_\-0-9]/i', $string))
{
echo "not valid string";
}
Explanation:
- [] => character class definition
- ^ => negate the class
- a-z => chars from 'a' to 'z'
- _ => underscore
- - => hyphen '-' (You need to escape it)
- 0-9 => numbers (from zero to nine)
The 'i' modifier at the end of the regex is for 'case-insensitive' if you don't put that you will need to add the upper case characters in the code before by doing A-Z