是的,验证访问parent.parent

s-l*_*ndz 9 javascript forms yup

我正在使用yup模块来验证我的表单。我想访问父级以测试该值。

我的架构:

enabled: yup.boolean(),
contactDetail: yup.object().shape({
  phoneNumber1: yup.string().nullable(),
  phoneNumber2: yup.string().nullable(),
  email: yup.string().test('email', 'test', async function() {
    // test enabled value
  })
}),
Run Code Online (Sandbox Code Playgroud)

该方法when可以在同一级别访问,而不是父级。

有人有主意吗?

Dip*_* KC 12

我也遇到过类似的问题。我成功地使用了这个解决方案。

想法:将整个表单数据作为上下文传递给模式并使用访问任何表单值

this.options.context

  const schema = yup.object().shape({
        enabled: yup.boolean(),
        contactDetail: yup.object().shape({
          phoneNumber1: yup.string().nullable(),
          phoneNumber2: yup.string().nullable(),
          email: yup.string().test('email', 'test', async function () {
            // this.options.context.enabled
           
          }),
        }),
      });
Run Code Online (Sandbox Code Playgroud)

传递上下文

没有福米克

验证时将表单数据作为上下文发送

 schema.validateSync(data, {context: form_data})
Run Code Online (Sandbox Code Playgroud)

与福米克

使用validate而不是validationSchema

Pass your Form data as 4th argument in validateYupSchema which represents context and can be accessed later in schema.

Pass your schema as 2nd argument in validateYupSchema.

    <Formik
      validate={(value) => {
        try {
          validateYupSchema(value, schema, true, value);
        } catch (err) {
          return yupToFormErrors(err); //for rendering validation errors
        }

        return {};
      }}

       onSubmit={} />
Run Code Online (Sandbox Code Playgroud)

Following is for the asynchronous validation with Formik.

    <Formik
      validate={async (value) => {
        try {
          await validateYupSchema(value, schema, false, value);
        } catch (err) {
          return yupToFormErrors(err); //for rendering validation errors
        }

        return {};
      }}

       onSubmit={} />
Run Code Online (Sandbox Code Playgroud)


小智 0

您可以使用https://github.com/jquense/yup#mixedtestname-string-message-string--function-test-function-schema中提供的测试方法。如下例所示,您可以使用 this.parent 访问 test() 内的一级父级详细信息。

amount: Yup.string().test('amount-test3', 'amount is required', function (value) {
                    const { description } = this.parent;
                    return !(!!description && !Number(value));
                  })
Run Code Online (Sandbox Code Playgroud)