Custom Pattern Rules for Fluent Forms Fields
Validates chosen Fluent Forms 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_ff_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.' ),
);
add_filter( 'fluentform/validation_errors', function ( $errors, $data ) use ( $wpide_ff_patterns ) {
foreach ( $wpide_ff_patterns as $name => $rule ) {
$value = isset( $data[ $name ] ) && is_string( $data[ $name ] ) ? trim( $data[ $name ] ) : '';
if ( '' !== $value && ! preg_match( $rule[0], $value ) ) {
$errors[ $name ] = array( $rule[1] );
}
}
return $errors;
}, 10, 2 );
Notes
Keys are field names (the Name Attribute in the field's Advanced Options); 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.