如何在使用 yup 验证对象模式时出现第一个错误

How to get first error while using yup to validate object schema

我正在使用 Yup 根据验证模式验证嵌套数据对象。我想检索第一个验证错误的路径。我试过 validate() 是的。它有选项 abortEarly 默认为真。所以在那种情况下应该返回第一个错误。

但是,我总是遇到最后一个错误。我不确定我错过了什么。

下面是我目前试过的代码。

  const validationSchema = Yup.object().shape({
    basicDetails: Yup.object().shape({
      firstName: Yup.string().required("Required first name"),
      lastName: Yup.string().required("Required last name"),
      gender: Yup.string().required("Required gender"),
      phoneNumber: Yup.string().required("Required phone number"),
      emailId: Yup.string().required("Email id is required")
    }),
    educationDetails: Yup.object().shape({
      graduationDegree: Yup.string().required("Required graduation degree"),
      postGraduationDegree: Yup.string().required(
        "Required post graduation degree"
      ),
      registrationNumber: Yup.string().required("Required registration number"),
      workExperience: Yup.string().required("Required work experience")
    })
  });

  const dataObject = {
    basicDetails: {
      firstName: "Nik",
      lastName: "Test",
      gender: "male",
      phoneNumber: "9876543210",
      emailId: ""
    },
    educationDetails: {
      graduationDegree: "Degree 1",
      postGraduationDegree: "Postgraduation Degree 1",
      registrationNumber: "",
      workExperience: ""
    }
  };

  const validateSchema = async () => {
    const validationResult = await validationSchema
      .validate(dataObject)
      .catch((err) => {
        return err;
      });
    // this returns last error. however, as per the documentation, it should return the first error.
    console.log(validationResult.errors, validationResult.params);

    const validationResult1 = await validationSchema
      .validate(dataObject, { abortEarly: false })
      .catch((err) => {
        return err;
      });
    // this returns array of all errors in correct order.
    console.log(validationResult1.errors);
  };


Here 是最小样本的代码沙箱 link。

我也尝试了简单模式,但得到了相同的结果。

这可能是适合您的解决方案。您的模式的当前结构不是嵌套的,而是一个对象数组。我认为如果您将结构更改为以下内容,您将获得所需的结果:

const validationSchemaNested = Yup.object().shape({
  basicDetails: Yup.object().shape({
    firstName: Yup.string().required("Required first name"),
    lastName: Yup.string().required("Required last name"),
    gender: Yup.string().required("Required gender"),
    phoneNumber: Yup.string().required("Required phone number"),
    emailId: Yup.string().required("Email id is required"),
    educationDetails: Yup.object().shape({
      graduationDegree: Yup.string().required("Required graduation degree"),
      postGraduationDegree: Yup.string().required("Required post graduation degree"),
      registrationNumber: Yup.string().required("Required registration number"),
      workExperience: Yup.string().required("Required work experience")
    })
  }),

});


const dataObjectNested = {
  basicDetails: {
    firstName: "Nik",
    lastName: "Test",
    gender: "male",
    phoneNumber: "9876543210",
    emailId: "",
    educationDetails: {
      graduationDegree: "Degree 1",
      postGraduationDegree: "Postgraduation Degree 1",
      registrationNumber: "",
      workExperience: ""
    }
  }
};

我像这样玩了一会儿,它似乎按照你想要的方式工作。

我认为您需要使用 abortEarly: false 进行验证,然后使用第一个错误。原因是,abortEarly 没有按照我们的预期去做。一旦发现一个错误,它不会停止进一步的验证。由于验证是 运行 在架构的每个级别并行进行。

因此,我认为这就是您或多或少需要做的事情:

  const validateNestedSchema = async () => {
    const validationResult = await validationSchemaNested
      .validate(dataObjectNested, { abortEarly: false })
      .catch((err) => {
        return err;
      });
    console.log(validationResult.inner[0].path); // gives "basicDetails.emailId" 
  };

the forked sandbox,如果需要


FWIW,他们似乎在 this issue 中讨论验证链的选项,但似乎还没有 conclusion/implementation。