I'm validating my contact form using PHP and I've used the following code:
if (ctype_alpha($name) === false) {
$errors[] = 'Name must only contain letters!';
}
This code is works fine, but it over validates and doesn't allow spaces. I've tried ctype_alpha_s
and that comes up with a fatal error.
Any help would be greatly appreciated
PHP | ctype_alpha() (Checks for alphabetic value) A ctype_alpha() function in PHP used to check all characters of a given string are alphabetic or not. If all characters are alphabetic then return True otherwise return False. Parameters Used: $text :- It is a mandatory parameter which specifies the string.
One for the UTF-8 world that will match spaces and letters from any language.
if (!preg_match('/^[\p{L} ]+$/u', $name)){
$errors[] = 'Name must contain letters and spaces only!';
}
Explanation:
This will also match names like Björk Guðmundsdóttir as noted in a comment by Anthony Hatzopoulos above.
Regex is overkill and will perform worse for such a simple task, consider using native string functions:
if (ctype_alpha(str_replace(' ', '', $name)) === false) {
$errors[] = 'Name must contain letters and spaces only';
}
This will strip spaces prior to running the alpha check. If tabs and new lines are an issue you could consider using this instead:
str_replace(array("\n", "\t", ' '), '', $name);
ctype_alpha only checks for the letters [A-Za-z]
If you want to use it for your purpose, first u will have to remove the spaces from your string and then apply ctype_alpha.
But I would go for preg_match to check for validation. You can do something like this.
if ( !preg_match ("/^[a-zA-Z\s]+$/",$name)) {
$errors[] = "Name must only contain letters!";
}
if (ctype_alpha(str_replace(' ', '', $name)) === false) {
$errors[] = 'Name must contain letters and spaces only';
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With