Contact Form 7 Regular Expression Validation

Viewed 6896

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;
}
2 Answers
Related