10. Validation Filters | Form Forge - Build Forms with AI in Seconds
Download Log in

10. Validation Filters

Developer Guide

Filters that allow you to modify field validation, sanitization, and custom server-side checks.

formforge_sanitize_field

Modify or override the sanitized value of a field before it is stored. Receives the sanitized value and the full field definition.

php
add_filter( 'formforge_sanitize_field', function( $value, $field ) {
    // Force uppercase for a postal code field
    if ( ( $field['id'] ?? '' ) === 'field_zipcode' ) {
        return strtoupper( trim( $value ) );
    }
    return $value;
}, 10, 2 );

Custom Server-Side Validation via formforge_before_submit

The formforge_before_submit action can also be used for custom validation. Call wp_send_json_error() to block the submission and show per-field errors.

Email domain whitelist:
php
add_action( 'formforge_before_submit', function( $form_id, $data, $form ) {
    if ( $form_id !== 5 ) return;

    $allowed_domains = [ 'company.com', 'partner.org' ];
    foreach ( $data as $field_id => $field ) {
        if ( ( $field['type'] ?? '' ) !== 'email' ) continue;

        $domain = substr( strrchr( $field['value'], '@' ), 1 );
        if ( ! in_array( $domain, $allowed_domains, true ) ) {
            wp_send_json_error( [
                'message' => 'Only company email addresses are accepted.',
                'errors'  => [ $field_id => 'Please use your company email.' ],
            ] );
        }
    }
}, 10, 3 );
Phone number format enforcement:
php
add_action( 'formforge_before_submit', function( $form_id, $data, $form ) {
    foreach ( $data as $field_id => $field ) {
        if ( ( $field['type'] ?? '' ) !== 'phone' ) continue;
        $phone = preg_replace( '/[^0-9+]/', '', $field['value'] );
        if ( strlen( $phone ) < 10 || strlen( $phone ) > 15 ) {
            wp_send_json_error( [
                'message' => 'Please provide a valid phone number.',
                'errors'  => [ $field_id => 'Phone must be 10-15 digits.' ],
            ] );
        }
    }
}, 10, 3 );

Built-in Validation Pipeline

ValidationApplies ToRule
Required checkAllField must have a non-empty value
Email formatemailis_email() WordPress function
Phone formatphoneRegex: ^[+ds-()]{7,20}$
URL formaturlfilter_var with FILTER_VALIDATE_URL
Number boundsnumber, rangemin / max comparison
Character lengthtext, textareamin_length / max_length
Custom regextextUser-defined pattern with custom error message
File typefile_uploadMIME type whitelist
File sizefile_upload10 MB maximum

Forge AI Assistant Online

Hi! I'm the Form Forge AI assistant. Ask me anything about the plugin — setup, features, troubleshooting, or development.

Just now
Powered by Forge AI · Browse docs