简体   繁体   English

如何在 ReactJs 中有条件地更改 Yup 验证

[英]How to change Yup validation conditionally in ReactJs

Hi all I have following code: my code大家好,我有以下代码:我的代码

I have two custom inputs components first one is common input second one checkbox:我有两个自定义输入组件第一个是通用输入第二个复选框:

      const MyTextInput = ({ label, ...props }) => {
        const [field, meta] = useField(props);
        return (
          <>
            <label htmlFor={props.id || props.name}>
              {label} <span>*</span>
            </label>
            <div>
              <input {...field} {...props} />
            </div>
            {meta.touched && meta.error ? <div>{meta.error}</div> : null}
          </>
        );
      };



    const MyCheckbox = ({ children, ...props }) => {
        const [field, meta] = useField({ ...props, type: "checkbox" });
        return (
          <div>
            <label>
              <input type="checkbox" {...field} {...props} />
              <span> {children}</span>
            </label>
            {meta.touched && meta.error ? (
              <div>{meta.error}</div>
            ) : null}
          </div>
        );
      };

I am using that components to create inputs for my form:我正在使用这些组件为我的表单创建输入:

          <MyTextInput
            label="validity"
            name="validity"
            type="date"
            disabled={a}
          />

          <MyCheckbox name="withoutLimitations" onClick={checkMe}>
            without Limitation
          </MyCheckbox>


          <MyTextInput
            label="number Of Uses "
            name="numberOfUses"
            type="text"
            disabled={b}
          />
          <MyCheckbox name="withoutLimitations_1" onClick={checkMe1}>
            without Limitation
          </MyCheckbox>

Also I am using Yup for creating validation:我也使用 Yup 来创建验证:

       validationSchema={Yup.object({
          validity: Yup.date().required(),
          numberOfUses: Yup.number().required()
        })}

Now my question is how can I change my validation schema when I am checking one of checkboxes.现在我的问题是当我检查其中一个复选框时如何更改我的验证模式。

For example if I am checking first checkbox that mean that date form should become disabled and value should become null no meter what user choose before checking the checkbox.例如,如果我选中第一个复选框,这意味着日期表单应该被禁用并且值应该变为 null 没有测量用户在选中复选框之前选择的内容。

with useState I able conditionally enable or disable the inputs but can't change validation schema, because when input don't have any data then I am pressing on submit button there was nothing happen.使用 useState 我可以有条件地启用或禁用输入,但不能更改验证模式,因为当输入没有任何数据时,我按下提交按钮时没有任何反应。

Please help me to resolve this problem请帮我解决这个问题

I would solve it like this:我会这样解决它:

  const validationSchema = Yup.object({
    validity: a ? Yup.date() : Yup.date().required(),
    numberOfUses: b ? Yup.number() : Yup.number().required()
  })

and put it to Formik :并将其放入Formik

validationSchema={validationSchema}

or you can also improve it, reduce the component's rerender by using the useMemo :或者你也可以改进它,使用useMemo减少组件的重新渲染:

  const validationSchema2 = React.useMemo(
    () =>
      Yup.object({
        validity: a ? Yup.date() : Yup.date().required(),
        numberOfUses: b ? Yup.number() : Yup.number().required(),
      }),
    [a, b],
  )

After researching I found the answer.经过研究,我找到了答案。 Here is example for only first input and checkbox这是仅第一个输入和复选框的示例

    withoutLimitations: Yup.boolean(),

    validity: Yup.date().when("withoutLimitations", {
            is: false,
            then: Yup.date().required(),
    }),

Also I changed my date input because safari don't support <input type="date" /> .我还更改了日期输入,因为 safari 不支持<input type="date" /> Now it looked like this:现在它看起来像这样:

     const [check, setCheck] = useState(false);

      <MuiPickersUtilsProvider
                      utils={DateFnsUtils}
                      locale={ruLocale}
                    >
                      <KeyboardDatePicker
                        format="MM/dd/yyyy"
                        value={check ? null : beforeDate}
                        onChange={(value) => {
                          formProps.setFieldValue("validity", value);
                          setBeforeDate(value);
                        }}
                        autoOk={true}
                      />

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM