20

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
  • 2
    what exactly should your validation result be and what did you try? Commented Apr 10, 2013 at 8:11
  • Show us some valid and invalid inputs Commented 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 "-" Commented Apr 10, 2013 at 8:16
  • For example, jay123: valid 1234:invalid ....: invalid jay.kum:valid Commented Apr 10, 2013 at 8:20
  • @jayantkumar did my answer meets your need? Commented Apr 10, 2013 at 10:53

4 Answers 4

35

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

Sign up to request clarification or add additional context in comments.

1 Comment

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.
24

Try this

// Validate alphanumeric
if (preg_match('/^[a-zA-Z]+[a-zA-Z0-9._]+$/', $input)) {
    // Valid
} else {
    // Invalid
}

1 Comment

This solution is not working on Turkish language characters. Thank you
3

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

Comments

1

I'm sort of new to regex, but I would do it this way:

preg_match('/^[\w.-]+$/', input)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.