gform-react
Back to Guides

Custom Validation

Write rules the native constraint API can't express - cross-field checks, conditional logic, or delegating to Yup/Zod - with GValidator.withCustomValidation.

When a native constraint can't express your rule - for example, comparing two fields - use withCustomValidation. The handler receives the current input and all fields, so it can validate one field against another. Custom rules are registered on the same validators object as native constraints.

const validators: GValidators<SignUpForm> = {
  confirmPassword: new GValidator().withCustomValidation((input, fields) => {
    if (input.value !== fields.password.value) {
      input.errorText = "Passwords do not match";
      return true; // ⚠️ return true to signal an ERROR
    }
    return false; // valid
  }),
};
Return value semantics

A custom validator returns true when the field is invalid and false when it's valid. Set input.errorText yourself to provide the message. (You can also return a RegExp/string pattern - the field is then valid only if the value matches it.)

Re-validating a dependent field: validatorDeps

A cross-field rule only re-runs when its own field changes. If confirmPassword depends on password, edit password and the previously-entered confirmPassword won't re-check on its own. Give the dependent field validatorDeps so editing password also re-runs confirmPassword's validator:

<GInput formKey="password" type="password" required element={/* … */} />
<GInput formKey="confirmPassword" required validatorDeps={["password"]} element={/* … */} />

See validatorDeps for the full contract, and the Sign-up & Validation example for this wired up end to end.

Try it live

A cross-field rule: confirm must match password. confirm declares validatorDeps={["password"]}, so editing password re-validates confirm and a previously-matching value doesn't go stale.

Loading playground…

Next

  • Async Validation - for rules that need a server round-trip.
  • Schema Validation - drive the whole form from a single Zod, Yup, or other Standard Schema.
  • GValidator - the class reference: inheritance, the mutation gotcha, execution order, and dev-mode diagnostics.