# Custom Pattern Rules for WPForms Text Fields

> Validates WPForms single-line text fields against your own patterns, such as postcodes, order numbers or VAT IDs, chosen per field with a CSS class.

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

## Code

```php
// CSS class => array( pattern, error message ).
$wpide_wpf_patterns = array(
    'wpide-postcode' => array( '/^[A-Za-z0-9 \-]{3,10}$/', 'Please enter a valid postcode.' ),
    'wpide-order'    => array( '/^#?\d{4,10}$/', 'Order numbers contain 4 to 10 digits.' ),
);

add_action( 'wpforms_process_validate_text', function ( $field_id, $field_submit, $form_data ) use ( $wpide_wpf_patterns ) {
    $css   = isset( $form_data['fields'][ $field_id ]['css'] ) ? preg_split( '/\s+/', (string) $form_data['fields'][ $field_id ]['css'] ) : array();
    $value = trim( (string) $field_submit );

    if ( '' === $value ) {
        return;
    }

    foreach ( $css as $class ) {
        if ( isset( $wpide_wpf_patterns[ $class ] ) && ! preg_match( $wpide_wpf_patterns[ $class ][0], $value ) ) {
            $process = method_exists( wpforms(), 'obj' ) ? wpforms()->obj( 'process' ) : wpforms()->process;
            $process->errors[ $form_data['id'] ][ $field_id ] = $wpide_wpf_patterns[ $class ][1];
            return;
        }
    }
}, 10, 3 );
```

## Notes

Give a text field one of the CSS classes from the list at the top (Advanced tab); 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 WPForms Text 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/
