Custom Pattern Rules for Contact Form 7 Fields
Validates chosen Contact Form 7 fields against your own patterns, such as postcodes, order numbers or membership IDs, each with its own error message.
Opens WPIDE on
Code
// Field name => array( pattern, error message ).
$wpide_cf7_patterns = array(
'postcode' => array( '/^[A-Za-z0-9 \-]{3,10}$/', 'Please enter a valid postcode.' ),
'order-number' => array( '/^#?\d{4,10}$/', 'Order numbers contain 4 to 10 digits.' ),
);
$wpide_cf7_pattern_check = function ( $result, $tag ) use ( $wpide_cf7_patterns ) {
if ( ! isset( $wpide_cf7_patterns[ $tag->name ] ) ) {
return $result;
}
$value = isset( $_POST[ $tag->name ] ) ? trim( (string) wp_unslash( $_POST[ $tag->name ] ) ) : '';
if ( '' !== $value && ! preg_match( $wpide_cf7_patterns[ $tag->name ][0], $value ) ) {
$result->invalidate( $tag, $wpide_cf7_patterns[ $tag->name ][1] );
}
return $result;
};
add_filter( 'wpcf7_validate_text', $wpide_cf7_pattern_check, 20, 2 );
add_filter( 'wpcf7_validate_text*', $wpide_cf7_pattern_check, 20, 2 );
Notes
Keys are field names from your form; patterns are PHP regular expressions matched against the whole value.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.