是的,非必填字段的验证 [英] Yup validation for a non-required field
问题描述
我的项目中有一个配置文件创建表单,我使用 react-hooks-form 和 yup 库进行验证.
I have a profile creation form in my project for which i am using react-hooks-form and yup library for validation.
在表单中有一个名为 Github-Username 的字段,这是可选的.但是我想验证它是否用户输入了用户名并且它应该超过 2 个字符,类似这样.
In the form there is one field named Github-Username which is optional. But i want to validate it if users enters the username and it should be more than 2 characters, something like that.
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),
});
//表单域
<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>
这是我目前编写的架构,不适用于 githubUsername.如果它是空的,它会显示错误.我只想在它不为空时进行验证.有这方面的线索吗?
This is the schema i have written so far, which is not working for githubUsername. It showing the error if it's empty. I want to validate only if it's not empty. Any leads on this?
推荐答案
批准的答案是正确的,但缺少一些信息.您需要向形状模式添加循环依赖
The approved answer is right but missing a bit of information. you need to add cyclic dependencies to the shape schema
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'],
]
);
这篇关于是的,非必填字段的验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!