# 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.

- Type: PHP
- Runs: Run everywhere
- Category: [Forms](https://wpide.com/library/category/forms/)
- Tags: contact-form-7, validation, regex
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/cf7-pattern-validation-rules/

## Code

```php
// 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 use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Custom Pattern Rules for Contact Form 7 Fields" in its snippet library and add it in one click; or create a new PHP snippet in WPIDE (or any code snippets plugin) and paste the code above. More snippets: https://wpide.com/library/
