Overview
There are many plugins that are available for contact form like contact form 7. This is one of the most popular and oldest WordPress contact form plugins around. However, despite its popularity, and document with tutorial are available but, many people still struggle with Contact Form 7 when it comes with customizing it or field validation.
Custom Validation CF7:
So, many would wonder why do we need custom validation for CF7? So, custom validation is required when you need validation like a user name input field or another scenario like show a custom error message.
As the official site mentions the working custom validation of the plugin, but I will try to make it easier for you to understand.
To validate, contact form 7 provides some hook for each form tag like ( wpcf7_validate_ + {type of the form-tag} ):
- Text : wpcf7_validate_text
- Text(required) : wpcf7_validate_text*
- Tel : wpcf7_validate_tel
- Tel(required) : wpcf7_validate_tel*
So, as you can see for every form tag there has been two hooks available one is for non-required and other is required form tag.
For Example, if you had a contact form like this:
So first we will validate the name field:
/*/---- Validate contact Form ----/*/add_filter( 'wpcf7_validate_text', 'custom_name_validation_filter', 20, 2 ); add_filter( 'wpcf7_validate_text*', 'custom_name_validation_filter', 20, 2 ); function custom_name_validation_filter( $result, $tag ) { if ( "first-name" == $tag->name || "last-name" == $tag->name ) { $name = isset( $_POST[$tag->name] ) ? $_POST[$tag->name] : ''; if ( $name != "" && !preg_match("/^[a-zA-Z]*$/",$name) ) { $result->invalidate( $tag, "The name entered is invalid." ); } } return $result; }
There will be two parameters going to pass the filter function which is $result and $tag.
$result is an instance of WPCF7_Validation class that manages a sequence of validation processes or more specifically where you can set your custom error message.
$tag is an instance of WPCF7_FormTag which represents your tag from which submitted with a value, you can access the name of the input field from the object as $tag->name and as for value, you can use $_POST[$tag->name].
After confirming form-tag we will check the value with regex or whatever method you apply for validation if it finds an error or wrong/invalid value we will send error message like $result->invalidate( $tag, “The name entered is invalid.” );
After everything is done we will return $result.
Conclusion
The example code above will validate the text field which had a name as ‘first-name’ and ‘last-name’ and it will provide the custom error message. Also, it will avoid the validation if the field value is empty. Also for a full user name or other validation, you can change match( preg_match ) condition.