laz*_*der 3 reactjs yup react-hooks react-hook-form
我的项目中有一个配置文件创建表单,我正在使用 react-hooks-form 和 yup 库进行验证。
在表单中有一个名为Github-Username 的字段,这是可选的。但是我想验证它是否用户输入了用户名并且它应该超过 2 个字符,类似这样。
const schema = yup.object().shape({
company: yup.string().min(3).required(),
website: yup.string(),
location: yup.string().min(2).required(),
skills: yup.string().min(3).required(),
githubUsername: yup.string().min(3).nullable().notRequired(),
bio: yup.string(),
});
const { register, handleSubmit, errors, touched } = useForm({
resolver: yupResolver(schema),
});
Run Code Online (Sandbox Code Playgroud)
// 表单域
<Form.Group controlId="formBasicGusername">
<Form.Label>Github Username</Form.Label>
<Form.Control
type="text"
name="githubUsername"
ref={register}
/>
<span className="text-danger text-capitalize">
{errors.githubUsername?.message}
</span>
</Form.Group>
Run Code Online (Sandbox Code Playgroud)
这是我到目前为止编写的架构,它不适用于 githubUsername。如果它是空的,它会显示错误。我只想在它不为空时进行验证。这有什么线索吗?
小智 36
批准的答案是正确的,但缺少一些信息。您需要向形状模式添加循环依赖关系
const schema = yup.object().shape(
{
company: yup.string().min(3).required(),
website: yup.string(),
location: yup.string().min(2).required(),
skills: yup.string().min(3).required(),
githubUsername: yup
.string()
.nullable()
.notRequired()
.when('githubUsername', {
is: (value) => value?.length,
then: (rule) => rule.min(3),
}),
bio: yup.string(),
},
[
// Add Cyclic deps here because when require itself
['githubUsername', 'githubUsername'],
]
);
Run Code Online (Sandbox Code Playgroud)
小智 5
githubUsername: yup.string().nullable().notRequired().when('githubUsername', {
is: value => value?.length,
then: rule => rule.min(3),
})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2023 次 |
| 最近记录: |