Skip to content

register

注册不受控/受控输入

</> register: (name: string, options?: RegisterOptions) => ({ ref, name, onChange, onBlur })

此方法允许你注册输入或选择元素并将验证规则应用于 React Hook Form。验证规则全部基于 HTML 标准,也允许自定义验证方法。

¥This method allows you to register an input or select element and apply validation rules to React Hook Form. Validation rules are all based on the HTML standard and also allow for custom validation methods.

属性

¥Props


名称类型描述
namestring输入的名称。
optionsRegisterOptions输入的行为。

返回

¥Return


名称类型描述
refReact.ref用于将钩子表单连接到输入的 React 元素引用。
namestring输入的名称正在注册。
onChangeChangeHandleronChange prop 用于订阅输入 change 事件。
onBlurChangeHandleronBlur prop 用于订阅输入 blur 事件。
NOTE

提交的值将如下所示:

¥This is how submitted values will look like:

输入名称提交结果
register("firstName"){ firstName: value }
register("name.firstName"){ name: { firstName: value } }
register("name.firstName.0"){ name: { firstName: [ value ] } }

选项

¥Options


通过选择注册选项,下面的 API 表将得到更新。

¥By selecting the register option, the API table below will get updated.

名称描述
ref
React.Ref
React 元素 ref
required
boolean
表示在提交表单之前,输入必须有一个值。

注意:此配置与 Web 约束 API 一致,用于必需的输入验证,对于对象或数组类型的输入,请改用验证函数。
maxLength
number
此输入可接受的值的最大长度。
minLength
number
此输入可接受的值的最小长度。
max
number
此输入可接受的最大值。
min
number
此输入可接受的最小值。
pattern
RegExp
输入的正则表达式模式。

注意:带有 /g 标志的 RegExp 会跟踪发生匹配的最后一个索引。
validate
Function |
Record<string, Function>
Validate 函数将自行执行,而不依赖于必需属性中包含的其他验证规则。

注意:对于对象或数组输入数据,建议使用验证函数进行验证,因为其他规则主要适用于字符串、字符串数组、数字和布尔值。
valueAsNumber
boolean
正常返回 Number。如果出现问题,NaN 将返回。
  • valueAs process is happening before validation.
  • Only applies to number input, but without any data manipulation.
  • Does not transform defaultValue or defaultValues.
valueAsDate
boolean
正常返回 Date。如果出现问题,Invalid Date 将返回。
  • valueAs process is happening before validation.
  • Only applies to input.
  • Does not transform defaultValue or defaultValues.
setValueAs
<T>(value: any) => T
通过运行函数返回输入值。
  • valueAs process is happening before validation. Also, setValueAs is ignored if either valueAsNumber or valueAsDate are true.
  • Only applies to text input.
  • Does not transform defaultValue or defaultValues.
disabled
boolean = false
disabled 设置为 true 将导致输入值为 undefined 并且输入控件被禁用。
  • disabled prop will also omit built-in validation rules.
  • For schema validation, you can leverage the undefined value returned from input or context object.
onChange
(e: SyntheticEvent) => void
在 change 事件中调用 onChange 函数事件。
onBlur
(e: SyntheticEvent) => void
在 blur 事件中调用 onBlur 函数事件。
value
unknown
为已注册的输入设置 value。此 prop 应在 useEffect 内部使用或调用一次,每次重新运行都会更新或覆盖你提供的输入值。
shouldUnregister
boolean
卸载后,输入将被取消注册,defaultValues 也将被删除。

注意:与 useFieldArray 一起使用时应避免使用此属性,因为在输入卸载/重新安装和重新排序后会调用取消注册函数。
deps
string | string[]
将为依赖输入触发验证,仅限于注册 api 不会触发。
名称描述
ref
React.Ref
React 元素 ref
required
string |
{ value: boolean, message: string }
表示在提交表单之前,输入必须有一个值。

注意:此配置与 Web 约束 API 一致,用于必需的输入验证,对于对象或数组类型的输入,请改用验证函数。
maxLength
{
  value: number,
  message: string
}
此输入可接受的值的最大长度。
minLength
{
  value: number,
  message: string
}
此输入可接受的值的最小长度。
max
{
  value: number,
  message: string
}
此输入可接受的最大值。
min
{
  value: number,
  message: string
}
此输入可接受的最小值。
pattern
{
  value: RegExp,
  message: string
}
输入的正则表达式模式。

注意:带有 /g 标志的 RegExp 会跟踪发生匹配的最后一个索引。
validate
Function |
Record<string, Function>
Validate 函数将自行执行,而不依赖于必需属性中包含的其他验证规则。

注意:对于对象或数组输入数据,建议使用验证函数进行验证,因为其他规则主要适用于字符串、字符串数组、数字和布尔值。
valueAsNumber
boolean
正常返回 Number。如果出现问题,NaN 将返回。
  • valueAs process is happening before validation.
  • Only applies to number input, but without any data manipulation.
  • Does not transform defaultValue or defaultValues.
valueAsDate
boolean
正常返回 Date。如果出现问题,Invalid Date 将返回。
  • valueAs process is happening before validation.
  • Only applies to input.
  • Does not transform defaultValue or defaultValues.
setValueAs
<T>(value: any) => T
通过运行函数返回输入值。
  • valueAs process is happening before validation. Also, setValueAs is ignored if either valueAsNumber or valueAsDate are true.
  • Only applies to text input.
  • Does not transform defaultValue or defaultValues.
disabled
boolean = false
disabled 设置为 true 将导致输入值为 undefined 并且输入控件被禁用。
  • disabled prop will also omit built-in validation rules.
  • For schema validation, you can leverage the undefined value returned from input or context object.
onChange
(e: SyntheticEvent) => void
在 change 事件中调用 onChange 函数事件。
onBlur
(e: SyntheticEvent) => void
在 blur 事件中调用 onBlur 函数事件。
value
unknown
为已注册的输入设置 value。此 prop 应在 useEffect 内部使用或调用一次,每次重新运行都会更新或覆盖你提供的输入值。
shouldUnregister
boolean
卸载后,输入将被取消注册,defaultValues 也将被删除。

注意:与 useFieldArray 一起使用时应避免使用此属性,因为在输入卸载/重新安装和重新排序后会调用取消注册函数。
deps
string | string[]
将为依赖输入触发验证,仅限于注册 api 不会触发。
RULES
  • 名称是必需的且唯一的(原生单选按钮和复选框除外)。输入名称支持点和括号语法,可让你轻松创建嵌套表单字段。

    ¥Name is required and unique (except native radio and checkbox). Input name supports both dot and bracket syntax, which allows you to easily create nested form fields.

  • 名称既不能以数字开头,也不能使用数字作为键名。请避免使用特殊字符。

    ¥Name can neither start with a number nor use number as key name. Please avoid special characters as well.

  • 我们仅使用点语法来保持 typescript 使用一致性,因此括号 [] 不适用于数组表单值。

    ¥We are using dot syntax only for typescript usage consistency, so bracket [] will not work for array form value.

    register('test.0.firstName'); // ✅
    register('test[0]firstName'); // ❌
  • Disabled input will result in an undefined form value. If you want to prevent users from updating the input, you can use readOnly or disable the entire fieldset. Here is an example.
  • To produce an array of fields, input names should be followed by a dot and number. For example: test.0.data
  • Changing the name on each render will result in new inputs being registered. It's recommended to keep static names for each registered input.
  • Input value and reference will no longer gets removed based on unmount. You can invoke unregister to remove that value and reference.
  • undefined{} 无法删除单独的注册选项。你可以改为更新单个属性。

    ¥Individual register option can't be removed by undefined or {}. You can update individual attribute instead.

    register('test', { required: true });
    register('test', {}); // ❌
    register('test', undefined); // ❌
    register('test', { required: false }); // ✅
  • There are certain keyword which need to avoid before conflicting with type check. They are ref, _f.

示例

¥Examples


注册输入或选择

¥Register input or select

import { useForm } from "react-hook-form"
export default function App() {
const { register, handleSubmit } = useForm({
defaultValues: {
firstName: "",
lastName: "",
category: "",
checkbox: [],
radio: "",
},
})
return (
<form onSubmit={handleSubmit(console.log)}>
<input
{...register("firstName", { required: true })}
placeholder="First name"
/>
<input
{...register("lastName", { minLength: 2 })}
placeholder="Last name"
/>
<select {...register("category")}>
<option value="">Select...</option>
<option value="A">Category A</option>
<option value="B">Category B</option>
</select>
<input {...register("checkbox")} type="checkbox" value="A" />
<input {...register("checkbox")} type="checkbox" value="B" />
<input {...register("checkbox")} type="checkbox" value="C" />
<input {...register("radio")} type="radio" value="A" />
<input {...register("radio")} type="radio" value="B" />
<input {...register("radio")} type="radio" value="C" />
<input type="submit" />
</form>
)
}

自定义异步验证

¥Custom async validation

import { useForm } from "react-hook-form"
import { checkProduct } from "./service"
export default function App() {
const { register, handleSubmit } = useForm()
return (
<form onSubmit={handleSubmit(console.log)}>
<select
{...register("category", {
required: true,
})}
>
<option value="">Select...</option>
<option value="A">Category A</option>
<option value="B">Category B</option>
</select>
<input
type="text"
{...register("product", {
validate: {
checkAvailability: async (product, { category }) => {
if (!category) return "Choose a category"
if (!product) return "Specify your product"
const isInStock = await checkProduct(category, product)
return isInStock || "There is no such product"
},
},
})}
/>
<input type="submit" />
</form>
)
}

视频

¥Video


提示

¥Tips


解构赋值

¥Destructuring assignment

const { onChange, onBlur, name, ref } = register('firstName');
// include type check against field path with the name you have supplied.
<input
onChange={onChange} // assign onChange event
onBlur={onBlur} // assign onBlur event
name={name} // assign name prop
ref={ref} // assign ref prop
/>
// same as above
<input {...register('firstName')} />

自定义注册

¥Custom Register

你还可以使用 useEffect 注册输入并将其视为虚拟输入。对于受控组件,我们提供了一个自定义钩子 useController控制器 组件来为你处理此过程。

¥You can also register inputs with useEffect and treat them as virtual inputs. For controlled components, we provide a custom hook useController and Controller component to take care this process for you.

如果你选择手动注册字段,则需要使用 setValue 更新输入值。

¥If you choose to manually register fields, you will need to update the input value with setValue.

register('firstName', { required: true, min: 8 });
<TextInput onTextChange={(value) => setValue('lastChange', value))} />

如何使用 innerRefinputRef

¥How to work with innerRef, inputRef?

当自定义输入组件未正确公开 ref 时,你可以通过以下方式使其工作。

¥When the custom input component didn't expose ref correctly, you can get it working via the following.

// not working, because ref is not assigned
<TextInput {...register('test')} />
const firstName = register('firstName', { required: true })
<TextInput
name={firstName.name}
onChange={firstName.onChange}
onBlur={firstName.onBlur}
inputRef={firstName.ref} // you can achieve the same for different ref name such as innerRef
/>