首页 > 解决方案 > 是的,不验证何时满足条件

问题描述

我有其他字段,只有在选中复选框时才会显示(布尔值为 true)。这些附加字段也需要验证,但使用 .when() 方法似乎不会对复选框为真作为条件做出反应。我的代码的验证部分如下所示:

  const schema = useMemo(
    () =>
      yup
        .object()
        .shape({
          type: yup
            .string()
            .label(translate('Forms.EmailForm.type.label'))
            .required(),
          person: yup
            .object()
            .shape({
              firstName: yup
                .string()
                .required()
                .trim()
                .min(1)
                .max(255)
                .label(
                  translate(
                    'Forms.EmailForm.firstName.label',
                  ),
                ),
              hasAddress: yup.boolean(),
              address: yup.boolean().when('hasAddress', {
                is: true,
                then: yup
                  .object()
                  .shape({
                    firstLine: yup
                      .string()
                      .required()
                      .max(255)
                      .label(
                        translate(
                          'Forms.EmailForm.address.firstLine.label',
                        ),
                      ),
                    secondLine: yup
                      .string()
                      .max(255)
                      .label(
                        translate(
                          'Forms.EmailForm.address.secondLine.label',
                        ),
                      ),
                  }),
              }),
            }),
        }),
    [],
  );

  const form = useForm<EmailForm>({
    resolver: yupResolver(schema),
    defaultValues: {
      type: 'PERSON',
    },
  });

标签: javascriptreactjstypescriptreact-hook-formyup

解决方案


推荐阅读