BlogGuides · October 4, 2026 · 5 min read

Contact Form 7 Custom Validation: Add and Test a Narrow Business Rule

Add a scoped CF7 custom validation rule, keep normalization separate and test accepted, rejected and corrected answers before release.

Two form cards with check and correction markers approaching a mint validation gate.
Conceptual illustration generated for this article; not a product screenshot or measured result.

A field can contain valid text and still fail a business rule. An inquiry reference might need a specific prefix, or two related answers might need to agree. Contact Form 7 custom validation lets a developer add those checks to the submission path instead of relying only on instructions beside the form.

Start with built-in field options. Custom PHP adds maintenance and should solve a defined problem that ordinary required fields, length bounds or choice lists cannot express. This guide explains a narrow reference-format example and a review process; it does not change any live form on this site.

Separate configuration warnings from submitted-input rules

The configuration validator reviews how a form and notification are configured. Input validation reviews the answers submitted by a visitor. A form with no configuration warnings can still need a business rule, and a business-rule callback cannot repair an incorrect mail template.

Write the rule in ordinary language first: “The optional inquiry reference is either empty or consists of REF-, followed by six digits.” State whether letter case is significant and what happens to leading or trailing spaces. That sentence becomes the acceptance criteria for code review and testing.

Scope the field name and tag type

CF7 documents validation hooks named wpcf7_validate_ followed by the form-tag type. The callback receives the validation result and the form-tag; it can attach an error with invalidate() and must return the result. Optional text and required text* have different hook names.

Use a field name unique to this workflow, such as inquiry-reference, and check that name inside the callback. If another form reuses it, the rule applies there too. For stricter isolation, have the developer add a reviewed form-level condition that suits the installed CF7 version.

<label>Inquiry reference (optional; REF- followed by six digits)
  [text inquiry-reference maxlength:10 placeholder "REF-123456"]
</label>

Implement a narrow server-side rule

The following original example belongs in a small site-specific plugin managed by a developer. It uses the WordPress request-unslashing helper, rejects an unexpected array and leaves an optional empty answer alone. It checks a format; it does not prove the reference exists or that the visitor owns a related record.

add_filter( 'wpcf7_validate_text', 'example_cf7_reference_rule', 20, 2 );

function example_cf7_reference_rule( $result, $tag ) {
    if ( 'inquiry-reference' !== $tag->name ) {
        return $result;
    }

    $raw = $_POST['inquiry-reference'] ?? '';
    if ( ! is_string( $raw ) ) {
        $result->invalidate( $tag, 'Enter one reference value.' );
        return $result;
    }

    $value = trim( wp_unslash( $raw ) );
    if ( '' !== $value && ! preg_match( '/\AREF-[0-9]{6}\z/', $value ) ) {
        $result->invalidate( $tag, 'Use REF- followed by six digits, or leave this blank.' );
    }

    return $result;
}

The example_cf7_ prefix is illustrative; choose a unique prefix for the actual site. This sample only hooks the optional text type used above. If the requirement changes to mandatory, review both the tag and the callback rather than making a partial edit.

Keep validation separate from normalization

This callback trims a local value to decide whether the format passes. It does not rewrite the submitted value that the Mail body or another connector receives. If a destination needs uppercase references without surrounding spaces, implement and test normalization separately.

That distinction prevents an easy reporting mistake: the form accepts an answer after a trimmed comparison, while a sheet stores the original spacing. Decide whether to allow that variation and where the canonical representation is created. Avoid silently changing a meaningful free-text answer as a side effect of validation.

Do not place network lookups inside a simple format check without a separate reliability design. A remote system timeout can turn an ordinary inquiry into a form failure. If reference existence must be verified, define timeouts, retry behavior and a user-friendly fallback before adding that dependency.

Build a test matrix before release

Use synthetic inputs in staging. This example should accept an empty value and REF-123456, reject REF-12345 and ref-123456, and reject text before or after the complete reference. Include leading spaces to verify the stated trim behavior. Check an unexpected array request through an authorized developer test.

Repeat the valid test after every rejected one so you can see that the visitor can recover. Review error placement, keyboard access and the notification contents. For the ordinary accepted answer, verify the same reference reaches the intended record without creating duplicates.

  • List accepted and rejected examples with expected results.
  • Confirm the hook matches the exact optional or required tag type.
  • Check another unrelated form remains unaffected.
  • Inspect both the error and the corrected submission.
  • Run the checks against the deployed WordPress and CF7 versions.
  • Give the callback an owner and a straightforward rollback path.

Interpret rejected attempts honestly

A rejected format is not automatically spam. A customer may have copied an older reference or misunderstood the prompt. Keep the business-rule outcome separate from spam classification, mail failures and successful handoffs when reviewing the form’s behavior.

Use our DOM event guide to understand browser-side signals, while keeping the rule itself on the server. A frontend listener can help describe an outcome; it should not be the only enforcement point for a requirement that matters.

Our free Svetlik Analytics for Contact Form 7 plugin provides submission trends and statistics. Its listing does not promise field-specific custom-rule reporting. Document the rule and its release date alongside whatever supported metrics you actually collect.

Sources