Halloween Sale 15% off Ends in See the plans
PHP

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.

Don’t have WPIDE yet? Install it on your site

Code

// 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 add this snippet

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.