mantine-form

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Mantine Form Skill

Mantine Form 技能指南

Core Workflow

核心工作流程

1. Set up the form

1. 搭建表单

tsx
const form = useForm({
  mode: 'controlled',       // or 'uncontrolled' for large forms
  initialValues: {
    email: '',
    age: 0,
  },
  validate: {
    email: isEmail('Invalid email'),
    age: isInRange({ min: 18 }, 'Must be at least 18'),
  },
});
tsx
const form = useForm({
  mode: 'controlled',       // 或针对大型表单使用'uncontrolled'
  initialValues: {
    email: '',
    age: 0,
  },
  validate: {
    email: isEmail('Invalid email'),
    age: isInRange({ min: 18 }, 'Must be at least 18'),
  },
});

2. Wire inputs with getInputProps

2. 使用getInputProps关联输入组件

tsx
<TextInput {...form.getInputProps('email')} label="Email" />
<NumberInput {...form.getInputProps('age')} label="Age" />
For checkboxes pass
{ type: 'checkbox' }
:
tsx
<Checkbox {...form.getInputProps('agreed', { type: 'checkbox' })} label="I agree" />
tsx
<TextInput {...form.getInputProps('email')} label="Email" />
<NumberInput {...form.getInputProps('age')} label="Age" />
对于复选框,需传递
{ type: 'checkbox' }
tsx
<Checkbox {...form.getInputProps('agreed', { type: 'checkbox' })} label="I agree" />

3. Handle submission

3. 处理提交

tsx
<form onSubmit={form.onSubmit((values) => console.log(values))}>
  ...
  <Button type="submit">Submit</Button>
</form>
onSubmit
only calls the handler when validation passes. To handle failures:
tsx
form.onSubmit(
  (values) => save(values),
  (errors) => console.log('Validation failed', errors)
)
tsx
<form onSubmit={form.onSubmit((values) => console.log(values))}>
  ...
  <Button type="submit">Submit</Button>
</form>
仅当验证通过时,
onSubmit
才会调用处理函数。如需处理验证失败:
tsx
form.onSubmit(
  (values) => save(values),
  (errors) => console.log('Validation failed', errors)
)

Validation

验证

Rules object (most common)

规则对象(最常用)

tsx
validate: {
  name: isNotEmpty('Required'),
  email: isEmail('Invalid email'),
  password: hasLength({ min: 8 }, 'Min 8 chars'),
  confirmPassword: matchesField('password', 'Passwords do not match'),
}
tsx
validate: {
  name: isNotEmpty('Required'),
  email: isEmail('Invalid email'),
  password: hasLength({ min: 8 }, 'Min 8 chars'),
  confirmPassword: matchesField('password', 'Passwords do not match'),
}

Function (for cross-field logic)

函数式验证(用于跨字段逻辑)

tsx
validate: (values) => ({
  endDate: values.endDate < values.startDate ? 'End must be after start' : null,
})
tsx
validate: (values) => ({
  endDate: values.endDate < values.startDate ? 'End must be after start' : null,
})

When to validate

验证触发时机

tsx
validateInputOnChange: true,        // validate all fields on every change
validateInputOnChange: ['email'],    // validate specific fields only
validateInputOnBlur: true,          // validate on blur instead
tsx
validateInputOnChange: true,        // 每次变更时验证所有字段
validateInputOnChange: ['email'],    // 仅验证指定字段
validateInputOnBlur: true,          // 改为在失去焦点时验证

Modes

模式

ModeState storageRe-rendersInput props
'controlled'
(default)
React stateOn every change
value
+
onChange
'uncontrolled'
RefsNone
defaultValue
+
onChange
In uncontrolled mode, use
form.key('fieldPath')
as the React
key
prop when you need to force a re-render of an input.
模式状态存储重渲染情况输入组件属性
'controlled'
(默认)
React state每次变更时触发
value
+
onChange
'uncontrolled'
Refs
defaultValue
+
onChange
在非受控模式下,当你需要强制重新渲染输入组件时,使用
form.key('fieldPath')
作为React的
key
属性。

References

参考资料

  • references/api.md
    — Full API:
    useForm
    options, complete return value,
    useField
    ,
    createFormContext
    ,
    createFormActions
    , all built-in validators, key types
  • references/patterns.md
    — Code examples: nested objects, array fields, async validation, form context across components,
    transformValues
    ,
    useField
    standalone
  • references/api.md
    — 完整API:
    useForm
    选项、完整返回值、
    useField
    createFormContext
    createFormActions
    、所有内置验证器、键类型
  • references/patterns.md
    — 代码示例:嵌套对象、数组字段、异步验证、跨组件表单上下文、
    transformValues
    、独立使用
    useField