getConstraints
A helper that returns an object containing the validation attributes for each field by introspecting the zod schema.
1import { getConstraints } from '@conform-to/zod/v3/future';
2// or
3import { getConstraints } from '@conform-to/zod/v4/future';
4
5const constraint = getConstraints(schema);#Parameters
schema
The value to introspect. If it's not a valid zod schema, the function returns undefined.
#Examples
Deriving constraints from a schema
1import { getConstraints } from '@conform-to/zod/v3/future';
2// or
3// import { getConstraints } from '@conform-to/zod/v4/future';
4import { z } from 'zod';
5
6const schema = z.object({
7 title: z.string().min(5).max(20),
8 description: z.string().min(100).max(1000).optional(),
9 password: z
10 .string()
11 .regex(/[A-Z]/, 'Must contain an uppercase letter')
12 .regex(/[0-9]/, 'Must contain a number'),
13});
14const constraint = getConstraints(schema);
15// {
16// title: { required: true, minLength: 5, maxLength: 20 },
17// description: { required: false, minLength: 100, maxLength: 1000 },
18// password: {
19// required: true,
20// pattern: '^(?=.*(?:[A-Z]))(?=.*(?:[0-9])).*$',
21// },
22// }Passing constraints to useForm
Call getConstraints directly and pass the result to useForm to enable native HTML validation attributes (e.g. required, minLength, min, pattern) on your form fields:
1import { useForm } from '@conform-to/react/future';
2import { getConstraints } from '@conform-to/zod/v3/future';
3
4const { form, fields } = useForm({
5 constraint: getConstraints(schema),
6});Using with configureForms
Pass getConstraints to configureForms to automatically derive constraints for all forms without repeating it in every useForm call:
1import { configureForms } from '@conform-to/react/future';
2import { getConstraints } from '@conform-to/zod/v3/future';
3
4const { useForm } = configureForms({
5 getConstraints,
6});#Tips
Pattern limitations
The pattern generation is best-effort with the following limitations:
- Regex flags: The
i(case-insensitive) flag is not supported. Nopatternis generated for case-insensitive regexes or when the serialized regex is not a valid HTMLpatternunder the browser'svflag. - Backreferences: Numbered backreferences (
\1,\2, etc.) may break when multiple regex validators for the same field are combined into onepattern. Named backreferences (\k<name>) are more reliable, but each regex combined into the samepatternmust use unique group names.