Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Contact Form 7 Regular Expression Validation

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;
}
like image 316
Herowe Avatar asked Jan 29 '23 22:01

Herowe


2 Answers

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;
}
like image 132
Frits Avatar answered Feb 01 '23 11:02

Frits


Try negating it

if(preg_match('/[^a-z\-]/i', $value)){

I've also updated it to use /i, which will ignore case

like image 33
adprocas Avatar answered Feb 01 '23 13:02

adprocas