validation - PHP validate input alphanumeric plus a few symbols


Need a way to validate an input field (in PHP) so it can contain only the following:

  • Any letter
  • Any number
  • any of these symbols: - (dash) _ (underscore) @ (at) . (dot) or a SPACE

Field can start or end with any of these (but not a space, but I can trim it before passing into validation function), and contain none, one, or any number (so just a check to make sure everything in the input is one of the above).

I would like to be able to do something like this:

funcion is_valid ( $in_form_input ) {
  // returns true or false

if ( is_valid($_POST['field1']) ) {
  echo "valid";
} else {
  echo "not valid";



return !preg_match('/[^[email protected] 0-9A-Za-z]/', $in_form_input);



The Best way would be to use like 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;

People are also looking for solutions to the problem: php - Managing quotes when using CKEditor setData function


Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.