Contact Form 7 - Custom Validation
Asked Answered
F

7

8

I need to validate just one field (called 'Instance') to accept lowercase ASCII letters and numbers only, the first character also has to be a letter not a number. It will accept uppercase characters but we will need it to lowercase them on input. So if someone uses the instance name McDonalds it will be lowercased to mcdonalds (not just with CSS). Spaces are not allowed either.

Is this possible with CF7? If so please explain how.

I've already tried this custom validation method but even with the preset custom validation in the file it was just displaying the field shortcode rather than the field itself.

Thanks

Foulard answered 4/4, 2014 at 9:7 Comment(0)
B
13

From contactform7.com on Custom Validation → Validation as a Filter:

In Contact Form 7, a user-input validation is implemented as a filter function. The filter hook used for the validation varies depending on the type of form-tag and is determined as: wpcf7_validate_ + {type of the form-tag}. So, for text form-tags, the filter hook wpcf7_validate_text is used. Likewise, wpcf7_validate_email* is used for email* form-tags.

Let’s say you have the following email fields in a form:

  Email:         [email* your-email]
  Confirm email: [email* your-email-confirm]

The following listing shows code that verifies whether the two fields have identical values.

add_filter('wpcf7_validate_email*', 'custom_email_confirmation_validation_filter', 20, 2);

function custom_email_confirmation_validation_filter($result, $tag) {
    $tag = new WPCF7_FormTag($tag);

    if ('your-email-confirm' == $tag->name) {
        $your_email = isset($_POST['your-email']) ? trim($_POST['your-email']) : '';
        $your_email_confirm = isset($_POST['your-email-confirm']) ? trim($_POST['your-email-confirm']) : '';

        if ($your_email != $your_email_confirm) {
            $result->invalidate($tag, "Are you sure this is the correct address?");
        }
    }
    return $result;
}

Two parameters will be passed to the filter function: $result and $tag. $result is an instance of WPCF7_Validation class that manages a sequence of validation processes. $tag is an associative array composed of given form-tag components; as you saw in the previous recipe, you can use WPCF7_FormTag class to handle this type of data.

Look through the inside of the filter function. First, check the name of the form-tag to ensure the validation is applied only to the specific field (your-email-confirm).

The two email field values are then compared, and if they don’t match, $result->invalidate() will be called. You need to pass two parameters to the invalidate() method: the first parameter should be the $tag variable, and the second parameter is the validation error message that you want the field to display.

Lastly, don’t forget to return the $result.

Bonina answered 24/4, 2015 at 11:2 Comment(1)
For googlers: The WPCF7_Shortcode has been deprecated. You should instead use WPCF7_FormTag. See contactform7.com/2016/12/03/contact-form-7-46Effieeffigy
S
4

I had a similar issue for validating name fields, I added the following code in my functions.php, you could customize it by changing the regex

function my_wpcf7_validate_text( $result, $tag ) {

    $type = $tag['type'];
    $name = $tag['name'];
    $value = $_POST[$name] ;

    if ( strpos( $name , 'name' ) !== false ){
        $regex = '/^[a-zA-Z]+$/';
        $Valid = preg_match($regex,  $value, $matches );
        if ( $Valid > 0 ) {
        } else {
            $result->invalidate( $tag, wpcf7_get_message( 'invalid_name' ) );
        }
    }
    return $result;
}
add_filter( 'wpcf7_validate_text*', 'my_wpcf7_validate_text' , 10, 2 );

add_filter( 'wpcf7_messages', 'mywpcf7_text_messages' );
function mywpcf7_text_messages( $messages ) {
    return array_merge( $messages, array(
        'invalid_name' => array(
            'description' => __( "Name is invalid", 'contact-form-7' ),
            'default' => __( 'Name seems invalid.', 'contact-form-7' )
        )
    ));
}
Slosh answered 10/3, 2015 at 12:24 Comment(1)
1.Just put this code in function.php ? 2.How to determine this code will work in my Field only say textbox? 3.What changes should i do in admin panel 4. Do i need to add any extra attribute thru admin contact us form ?? There is nothing you explained about above points . You just pasted the code , thats it!Courbevoie
B
4

// Add custom validation for CF7 form fields

function is_company_email($email){ // Check against list of common public email providers & return true if the email provided *doesn't* match one of them
        if(
                preg_match('/@gmail.com/i', $email) ||
                preg_match('/@hotmail.com/i', $email) ||
                preg_match('/@live.com/i', $email) ||
                preg_match('/@msn.com/i', $email) ||
                preg_match('/@aol.com/i', $email) ||
                preg_match('/@yahoo.com/i', $email) ||
                preg_match('/@inbox.com/i', $email) ||
                preg_match('/@gmx.com/i', $email) ||
                preg_match('/@me.com/i', $email)
        ){
                return false; // It's a publicly available email address
        }else{
                return true; // It's probably a company email address
        }
}
function your_validation_filter_func($result,$tag){
        $type = $tag['type'];
        $name = $tag['name'];
        if('yourid' == $value){ // Only apply to fields with the form field name of "company-email"
                $the_value = $_POST[$name];
                if(!is_company_email($the_value)){ // Isn't a company email address (it matched the list of free email providers)
                        $result['valid'] = false;
                        $result->invalidate( $tag, wpcf7_get_message( 'invalid_email' ));
                }
        }
        return $result;
}

 add_filter( 'wpcf7_validate_email', 'your_validation_filter_func', 10, 2 ); 

// Email field or contact number field
  add_filter( 'wpcf7_validate_email*', 'your_validation_filter_func', 10, 2 );     // Req. Email field or contact number
Blueweed answered 11/5, 2016 at 13:21 Comment(1)
I have edited the code of Zafar S who has posted above. Few changes are made on the code and remember to change youridBlueweed
G
3

Please use this wordpress plugin

Jquery Validation For Contact Form 7 https://wordpress.org/plugins/jquery-validation-for-contact-form-7/

Graminivorous answered 10/11, 2014 at 14:1 Comment(1)
Aaron, Install this plugin, after installing the Contact Form 7 Plugin, Make the field as a Required field and add like, url/number/creditcard/date in "Class (optional) field". Use the below link for more : wordpress.org/plugins/jquery-validation-for-contact-form-7/…Graminivorous
D
2

You can add your own custom validation for a form field input by using the add_filter function.

For adding a custom validation for a textarea field you can add the following inside functions.php file in the root directory of your theme.

add_filter( 'wpcf7_validate_textarea*', 'custom_textarea_validation_filter', 1, 2 );

function custom_textarea_validation_filter( $result, $tag ) {
  $tag = new WPCF7_Shortcode($tag);
  $result = (object)$result;

  $name = 'project-synopsis';

  if ( $name == $tag->name ) {
    $project_synopsis = isset( $_POST[$name] ) ? trim( wp_unslash( (string) $_POST[$name] ) ) : '';

    if ( empty( $project_synopsis ) ) {
      $result->invalidate( $tag, "Please write a quick project synopsis." );
    }
  }

  return $result;
}

For me the trick was to cast the $result parameter to an object, because the invalidate method that is used to add the error message didn't work before casting.

Dihydrostreptomycin answered 29/8, 2018 at 13:21 Comment(0)
L
1

Try this plugin. It's allow to set custom validation message for each field in free version. URL : https://wordpress.org/plugins/cf7-custom-validation-message/

Leake answered 2/12, 2020 at 19:46 Comment(2)
I tried this plugin. I had two validation for one field - "your-name". But this plugin gives only one custom error message for that field. Does not work for all validation.Petunia
Plugins are for general purpose so you need to use custom hooks to validate is according to your need.Leake
I
0
var cf = jQuery("#contact_form").validate({
    rules: {
        'your-fname': {
            required: true
        },
        'your-lname': {
            required: true
        },
        'your-email': {
            required: true,
            email: true
        },
        'your-phone': {
            required: true,
            //phoneAu: true,
            rangelength: [5, 16]
        },
        'your-subject': {
            required: true
        }
    },
    messages: {
        'your-fname': {
            required: "Please enter your first name."
        },
        'your-lname': {
            required: "Please enter your last name."
        },
        'your-email': {
            required: "Please enter your email address.",
            email: "Please enter valid email address."
        },
        'your-phone': {
            required: "Please enter your phone number.",
            rangelength: "Please enter valid phone number."
        },
        'your-subject': {
            required: "Please enter your subject."
        }
    },
    errorPlacement: function (error, element) {
        error.insertAfter(element);
    },
    errorElement: "label",
    errorClass: "error"
});
Irresoluble answered 5/7 at 12:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.