Composition
Combine validators with V.all, V.any, V.not, and V.optional
Composition
Individual validators cover one rule. Composition combines them so a single field can express AND, OR, NOT, and OPTIONAL logic.
Available combinators
| Function | Behavior |
|---|---|
V.all([...rules], message?) | Every rule must pass (AND). The message defaults to the first failing rule's message. |
V.any([...rules], message?) | At least one rule must pass (OR). |
V.not(rule, message?) | The rule must fail (NOT). |
V.optional(rule) | Only validate when non-empty — empty values always pass. |
Examples
import { V } from "formify-js";
// AND: must be alphanumeric, 4–20 characters
const strongUsername = V.all([V.alphanumeric(), V.minLength(4), V.maxLength(20)]);
// OR: accept either an email or a phone number
const contact = V.any([V.email(), V.phone()], "Enter an email or a phone number");
// NOT: must not be the literal string "admin"
const notReserved = V.not(V.oneOf(["admin"]));
// OPTIONAL: only validated when the user typed something
const optionalUsername = V.optional(V.username());Using composed rules in a schema
Composed rules are Rule objects, so they slot into a field's validators array alongside plain flags:
validationSchema: {
contact: {
required: true,
validators: [
{ validator: V.any([V.email(), V.phone()]), message: "Enter an email or a phone number" },
],
},
username: {
required: true,
validators: [
{ validator: V.all([V.alphanumeric(), V.minLength(4), V.maxLength(20)]) },
],
},
}Default messages
Composed rules produce messages from their inner rules:
| Scenario | Message |
|---|---|
V.all fails | The message of the first failing inner rule |
V.any fails | The message argument, or a generic "must satisfy at least one rule" fallback |
V.not fails | The inverse of the inner rule's message |
V.optional with an empty value | No error — empty values pass |
Notes
V.optionalis the composition-level equivalent of "validate only if filled in"; therequiredflag is the opposite — an empty value must fail.- Composition works in any field, including
<FieldArray>items, becauseVreturns plain validation rule objects.