如何使用yup.addMethod()为国家名称和代码编写自定义模式验证



我正在尝试将使用yup的表单验证添加到使用formik的React表单组件中。我的验证似乎有效,但我觉得它太冗长了。

试图使用yup.addMethod()函数,但在语法上卡住了,或者这可能太过分了?

摘要:我想使用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()

function isValidCountryName(ref, msg) {
return yup.mixed().test({
name: 'isValidCountry',
exclusive: false,
message: msg || `${ref.path} must be a valid country name`,
params: {
reference: ref.path,
},
test(value) {
const isRightFormat = this.resolve(ref);
return isRightFormat; [//ASK] should be doing the checks or transformations here
},
});
}
yup.addMethod(yup.string, 'isValidCountryName', isValidCountryName)

有两种方法可以做到这一点:

  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);
  1. 使用自定义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.")
});

这是演示。

最新更新