如何在yup.validationSchema中添加和删除验证字段
const validationSchema = yup.object().shape({
password: yup
.string()
.label('Password')
.required()
.min(2, 'Seems a bit short...')
.max(10, 'We prefer insecure system, try a shorter password.'),
});
要添加验证,您可以使用concat,在此处查看文档:
https://github.com/jquense/yup#mixedconcatschema-schema
您可以定义基本验证并稍后添加其他验证。小心你,你只是相同类型的concat。
例:
const requiredSchema = Yup.string().required();
const min2Schema = Yup.string().min(2, 'Seems a bit short...');
const passwordSchema = Yup.string()
.label('Password')
.max(10, 'We prefer insecure system, try a shorter password.')
.concat(requiredSchema)
.concat(min2Schema);
所有模式都是.string()模式。你可以用对象连接一个对象,用字符串连接字符串,用数字连接数字等。
要进行条件验证,您只需添加内联条件:
let isRequired = true;
const nameAndPasswordSchemaObject = Yup.object().shape({
name: nameSchema.concat( isRequired ? requiredSchema : null ),
password: passwordSchema,
});
对于yup-objects也是如此:
const emailSchemaObject = Yup.object({
email: Yup.string().concat(requiredSchema)
});
const validationSchema = nameAndPasswordSchemaObject.concat(emailSchemaObject);
我希望有所帮助。
关于删除模式我在文档中看不到任何内容(但从不需要它)