我正在尝试将验证添加到字段中
现在,以下示例适用于第一次检查。它检查是否定义了myField,然后使用myValidation测试验证该字段:
// ✓ runs the validation when it's defined
// ✗ does not run the validation the field has the initial value (again)
const myValidation = Yup.string()
.min(10, 'Should have at least 10 characters')
.max(20, 'Should have at last 20 characters');
const validationSchema = yup.object({
myField: yup.string.when(['myField'], {
is: (myField) => {
return !!myField
},
then: myValidation(),
},
)}
但是如何将其与检查初始值结合起来?
我在考虑以下方面:
import * as yup from 'yup';
const myValidation = Yup.string()
.min(10, 'Should have at least 10 characters')
.max(20, 'Should have at last 20 characters');
yup.addMethod(Yup.string, 'requiredWhen', function() {
return this.test({
name: 'requiredWhen',
exclusive: true,
message: 'This is required',
test: function(value) {
const { context } = this.options;
const { myField: initialValue } = context;
if (value !== initialValue) {
// is this possible?
// then: myValidation()
}
return true;
}
})
});
const validationSchema = yup.object({
myField: yup.string().requiredWhen(),
});
const validate = (values, initialValues) => validationSchema
.validate(values, { abortEarly: false, context: initialValues })
.catch(err => {
throw yupToFormErrors(err);
});
const MyForm = ({ initialValues }) => (
<Formik
initialValues={initialValues}
validate={(values) => validate(values, initialValues)}
/>
);
但是我不确定如何在addMethod的测试中应用'then'。