-1

I want to check if an input field is not empty and if he has special characters. I tried this:

function stringValidator($field) {   

    if(!empty($field) && (!filter_var($field, FILTER_SANITIZE_STRING)))
    {

            return "You typed $field: please don't use special characters 
            '<' '>' '_' '/' etc.";

    } }

The PHP not even tried to validate this way. Any tips?

mickmackusa
  • 43,625
  • 12
  • 83
  • 136
Codeman
  • 1
  • 1
  • [This is not how FILTER_SANITIZE_STRING works](https://stackoverflow.com/a/23392684/965834) (it's badly documented though, to be fair). – Jeto Nov 04 '18 at 23:26

1 Answers1

0

A preg_match() call will work nicely.

Code: (Demo)

function stringValidator($field) {   
    if(!empty($field) && preg_match('~[^a-z\d]~i', $field)) {
            return "You typed $field: please don't use special characters '<' '>' '_' '/' etc.";
    }
    return "valid";  // empty or valid
}

$strings = ["hello", "what_the"];
foreach ($strings as $string) {
    echo "$string: " , stringValidator($string) , "\n";
}

Output:

hello: valid
what_the: You typed what_the: please don't use special characters 
            '<' '>' '_' '/' etc.

Or a ctype_ call:

Code: (Demo)

function stringValidator($field) {   
    if(!empty($field) && !ctype_alnum($field)) {
            return "You typed $field: please use only alphanumeric characters";
    }
    return "valid";  // empty or valid
}

$strings = ["hello", "what_the"];
foreach ($strings as $string) {
    echo "$string: " , stringValidator($string) , "\n";
}

Output:

hello: valid
what_the: You typed what_the: please use only alphanumeric characters
mickmackusa
  • 43,625
  • 12
  • 83
  • 136