0

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";
}
OneNerd
  • 6,442
  • 17
  • 60
  • 78

3 Answers3

4
return !preg_match('/[^-_@. 0-9A-Za-z]/', $in_form_input);
codeholic
  • 5,680
  • 3
  • 23
  • 43
  • There was basically the same question http://stackoverflow.com/questions/2284061/how-do-i-write-a-perl-regular-expression-that-will-match-a-string-with-only-these/2284442#2284442 – codeholic Feb 20 '10 at 19:11
  • wrapped this into a function and it worked as needed - thanks! – OneNerd Feb 20 '10 at 19:17
3

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;
    }
}
3

Use preg_match():

if (preg_match('!^[\w @.-]*$!', $input)) {
  // its valid
}

Note: \w is synonymous to [a-zA-Z0-9_].

cletus
  • 616,129
  • 168
  • 910
  • 942