我正在尝试使用yup
将表单验证添加到使用formik
的React表单组件中。我的验证似乎有效,但是我觉得它太冗长了。
尝试使用.addMethod()
的{{1}}函数,但是在语法上卡住了,或者这可能是过大的?
摘要:我想使用yup
将我的验证转换为实际方法。
实际验证:
yup.addMethod()
我使用import * as yup from 'yup'
const countryNameRegex = /[A-Za-z]/g;
const countryCodeRegex = /[a-zA-Z]{2,}/g;
const isRequired = 'Required Field'
const isCorrectFormat = 'The country name may contain only letters'
const countryValidationSchema = yup.object().shape({
name: yup.string()
.min(3, `country name must contain at least 3 characters`)
.matches(
countryNameRegex,
{
message: isCorrectFormat,
excludeEmptyStrings: true
}
)
.label(`Country Name`)
.required(isRequired),
code: yup.string()
.length(2, `The country code must be exactly 2 letters`)
.matches(
countryCodeRegex,
{
message: isCorrectFormat,
excludeEmptyStrings: true
}
)
.label('Country Code')
.required(isRequired),
});
export default countryValidationSchema;
yup.addMethod()
答案 0 :(得分:1)
您有两种方法可以做到这一点:
yup
的内置方法:// Using built-in methods
function isValidCountry1() {
return this.min(3, TOO_SMALL_ERROR_MESSAGE)
.matches(COUNTRY_NAME_REGEX, {
message: INVALID_FORMAT_ERROR_MESSAGE,
excludeEmptyStrings: true
})
.required(REQUIRED_ERROR_MESSAGE);
}
yup.addMethod(yup.string, "isValidCountry1", isValidCountry1);
test
函数:// Using custom test method
function isValidCountry2(message) {
return this.test("isValidCountry", message, function (value) {
const { path, createError } = this;
if (!value) {
return createError({ path, message: message ?? REQUIRED_ERROR_MESSAGE });
}
if (value.length < 3) {
return createError({ path, message: message ?? TOO_SMALL_ERROR_MESSAGE });
}
if (!value.match(COUNTRY_NAME_REGEX)) {
return createError({
path,
message: message ?? INVALID_FORMAT_ERROR_MESSAGE
});
}
return true;
});
}
yup.addMethod(yup.mixed, "isValidCountry2", isValidCountry2);
添加方法后,您可以在验证架构中使用它们:
const validationSchema = yup.object().shape({
country1: yup.string().isValidCountry1(),
country2: yup.mixed().isValidCountry2(),
country3: yup.mixed().isValidCountry2("Country format is invalid.")
});
这是DEMO。