【发布时间】:2021-08-30 19:32:07
【问题描述】:
我正在尝试使用 yup 和 react-hook-form 学习表单验证,并且理想情况下希望将验证设置为还需要至少两个不同名称的单选选项之一,但首先要了解为什么 isValid变量为假。
这是我的代码:
import React from "react";
import { useForm } from "react-hook-form";
import * as yup from "yup"
const App = () => {
const { register, handleSubmit, watch, errors } = useForm();
const onSubmit = async data => {
console.log('form data', data);
const isValid = await schema.isValid();
console.log('isValid', isValid);
}
return (
<>
{console.log('errors', errors)}
<form onSubmit={handleSubmit(onSubmit)}>
<input name="name" defaultValue="test" ref={register} />
<input name="nameTwo" ref={register({ required: true })} />
{errors.exampleRequired && <span>This field is required</span>}
<label>
<input
name="test"
type="radio"
ref={register}
value="test"
/>
</label>
<label>
<input
name="testTwo"
type="radio"
ref={register}
value="testTwo"
/>
</label>
<input type="submit" />
</form>
</>
);
}
const schema = yup.object().shape({
name: yup.string(),
nameTwo: yup.string().required(),
test: yup.string(),
testTwo: yup.string()
})
export default App
因此,架构只根据需要定义了一个字段 (nameTwo),但即使填写该字段,它仍然是错误的。为什么isValid 不正确?最好如何将两个单选按钮(test 或 testTwo)之一设为必需?
Stackblitz 演示:https://stackblitz.com/edit/react-93vahd
谢谢
【问题讨论】:
-
在第 9 行,您在没有任何参数的情况下调用了
schema.isValid()。此外,您可能会发现validation resolvers 很有用。