OneNerd
OneNerd

Reputation: 6552

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:

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

Upvotes: 0

Views: 8648

Answers (3)

ifreelancer.asia
ifreelancer.asia

Reputation: 311

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

Upvotes: 3

cletus
cletus

Reputation: 625007

Use preg_match():

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

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

Upvotes: 3

codeholic
codeholic

Reputation: 5848

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

Upvotes: 4

Related Questions