I'm trying to add regular expression validation to Contact Form 7 'last-name' field that will allow for hyphenated names. I have researched and written a function to allow for this, but it doesn't seemed to be working. Any help would be appreciated.
Here is the function I have written and placed in functions.php file...
add_filter('wpcf7_validate_text', 'custom_text_validation', 20, 2);
add_filter('wpcf7_validate_text*', 'custom_text_validation', 20, 2);
function custom_text_validation($result, $tag) {
$type = $tag['type'];
$name = $tag['name'];
if($name == 'last-name') {
$value = $_POST[$name];
if(!preg_match('[a-zA-Z\-]', $value)){
$result->invalidate($tag, "Invalid characters");
}
}
return $result;
}
So the first thing I think we will need to look at it is on your 5th and 6th lines. According to the CF7 documentation, the $tag
argument actually returns an object and not an array.
Which means that $tag['name']
and $tag['type']
should actually be $tag->name
and $tag->type
.
The second thing to address is your regex expression, now would be a good time to read up on Falsehoods Programmers Believe about Names. Basically, in short, there are a lot of last names that will not match if the criteria is MixedAlpha and a dash.
If, however, you are intent on cutting out a portion of potential users, might I suggest making use maček's basic regex listed on this SO answer as it will atleast include a few more potential valid last names.
This would turn your function into something like this:
add_filter('wpcf7_validate_text', 'custom_text_validation', 20, 2);
add_filter('wpcf7_validate_text*', 'custom_text_validation', 20, 2);
function custom_text_validation($result, $tag) {
$type = $tag->type; //object instead of array
$name = $tag->name; //object instead of array
if($name == 'last-name') {
$value = $_POST[$name];
if(!preg_match("/^[a-z ,.'-]+$/i", $value )){ //new regex statement
$result->invalidate($tag, "Invalid characters");
}
}
return $result;
}
Try negating it
if(preg_match('/[^a-z\-]/i', $value)){
I've also updated it to use /i
, which will ignore case
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