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
}),
};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
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.
Trigger it explicitly with dispatchChanges({}, { validate: true }):
<GInput
formKey="password"
type="password"
required
onChange={() => {
// re-check confirmPassword against the new password value
if (state.confirmPassword.value) {
state.confirmPassword.dispatchChanges({}, { validate: true });
}
}}
element={/* … */}
/>See the Sign-up & Validation example for this wired up end to end.
Try it live
A cross-field rule: confirm must match password. Editing password re-validates confirm via
dispatchChanges({}, { validate: true }), so a previously-matching value doesn't go stale.
Next
- Async Validation - for rules that need a server round-trip.
- Schema Libraries - optional: delegate to Yup, Zod, or any schema you already use.
- GValidator - the class reference: inheritance, the mutation gotcha, execution order, and dev-mode diagnostics.