Afr*_*har 4 javascript typescript reactjs yup formik
我想使用我的架构在其他字段的基础上验证一个字段。就像,如果 carType 是“SUV”,则最大“noOfPassengers”应该是 6,否则是 4。但是,它没有验证这种情况,我既无法调试它,也无法在控制台中收到任何错误。
const validationSchema = yup.object().shape({
location: yup
.string()
.required('location is required'),
destination: yup
.string()
.required('Destination is required'),
carType: yup
.string(),
noOfPassengers: yup
.string()
.when('carType', {
is: value => value && value === "SUV",
then: yup
.string()
.max(6, 'Max 6 passengers are required'),
otherwise: yup
.string()
.max(4, 'Max 4 passengers are required'),
}),
});
Run Code Online (Sandbox Code Playgroud)
您将 noOfPassengers 的值作为字符串进行比较,而它应该是一个数字,如下所示:
Yup.object().shape({
location: Yup
.string()
.required('location is required'),
destination: Yup
.string()
.required('Destination is required'),
carType: Yup
.string(),
noOfPassengers: Yup
.number()
.when('carType', {
is: value => value && value === "SUV",
then: Yup
.number()
.max(6, 'Max 6 passengers are required'),
otherwise: Yup
.number()
.max(4, 'Max 4 passengers are required'),
}),
});
Run Code Online (Sandbox Code Playgroud)
如果运行此命令,您应该会收到验证错误。你的逻辑条件也有缺陷。您也应该解决这个问题,但这不是这个答案的范围。
问题是
Yup.string()应该是Yup.number()因为你然后在比较它max。
| 归档时间: |
|
| 查看次数: |
11710 次 |
| 最近记录: |