I tried to look on here as to why this code is not working, got no where and now I’m hoping someone can help me out.
function validateData($string) {
if (empty($string)) {
return 'error';
} elseif (strlen($string) <= 1) {
return 'error';
} elseif (preg_match('[a-zA-Z0-9]+\ ?', $string)) {
return 'error';
} else {
return 'normal';
}
}
When I execute the above code, using:
echo validateData('Test');
echo validateData('Test!');
These both echo ‘normal’.. however, the second example contains the ‘!’ in the string and should return ‘error’ because of the preg_match statement in the above code.
Achievement Objective. Check a string to make sure that it is not EMPTY, that it is longer than 1 character and only contains a-z, A-Z, 0-9 or a space. So no special characters.
Thank you very much in advance to all answers, I really appreciate it!
Ken
If the string is empty, it will be equal to 0 when you ask for it’s string length, therefore testing empty($string) is useless since it is covered by the second test.
Using a regex adds complexity without benefit here, there is a dedicated function to return true or false for alphanumeric string: ctype_alnum($string)
Your function can just be: