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.
Opens WPIDE on
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
- 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.