如何使用yup.addMethod()输入国家名称和代码来编写自定义架构验证?

时间:2020-03-04 11:52:00

标签: reactjs validation schema formik yup

我正在尝试使用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()

1 个答案:

答案 0 :(得分:1)

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

  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.")
});

这是DEMO