问题描述
因此,在学习时,我找到了表格-yup用于验证。但是我遇到了问题
所以我将解释问题陈述以及到目前为止我已经尝试过的事情。
因此,用例是我有一个选择字段,其中有两个选项:常驻和非常驻,因此基于选择,我有我要渲染的不同字段
- 居民:名字,姓氏
- 非居民:护照号码,国家/地区,州
因此,在这里我想分割模式,并根据选择,我想添加其他字段模式以进行验证。
const required = () => "Field is required";
const resident_schema = object({
first_name: string().required(required).nullable(),last_name: string().required(required).nullable(),});
const non_resident_schema = object({
passport_number: string().required(required).nullable(),country: object().required(required).nullable(),state: object().required(required).nullable(),});
const schemaBasedCitizen = {
RESIDENT: resident_schema,NON-RESIDENT: non_resident_schema,};
export const validationSchema = object().shape({
citizen: object().required(required).nullable(),{ ...object().when("citizen",{
is: (value) => !!schemaBasedCitizen[value.toupperCase()],then: (value) => schemaBasedCitizen[value.toupperCase()],}) },});
我的html包含
<select>
<option disabled selected value> -- select an option -- </option>
<option value='resident'>Resident</option>
<option value='non-resident'>Non-Resident</option>
</select>
由于关键要求,我无法传播,所以有办法实现这一目标。
更新
当值驻留在选择字段中时的模式
export const validationSchema = object().shape({
citizen: object().required(required).nullable(),first_name: string().required(required).nullable(),});
当值不在选择字段中时驻留的模式
export const validationSchema = object().shape({
citizen: object().required(required).nullable(),passport_number: string().required(required).nullable(),});
基本上,验证是动态的,基于“公民选择”字段上的值。
解决方法
是的,它只能使用when
引用同级字段(或上下文)。
您的citizen
字段不是该对象其余部分的兄弟姐妹,并且不能用于有条件地更改对象架构,它是该对象的子,因此您可以不会通过when
将该字段作为同级字段引用。
一种实现所需目标的方法是使用lazy模式:
import { lazy } from 'yup';
const residentSchema = ...
const nonResidentSchema = ...
export const validationSchema = lazy(({citizen}) => citizen === 'resident' ? residentSchema : nonResidentSchema);