【问题标题】:React Formik Yup validation for checking input value less than a numberReact Formik Yup 验证以检查输入值是否小于数字
【发布时间】:2021-12-29 12:36:57
【问题描述】:

我有一个使用 Formik 构建的表单。表单中有两个单选按钮,单击一个单选按钮时会出现一个输入字段。我需要使用 Yup 验证来验证该输入字段。该值应小于 9999.99,并且它也可以接受整数和十进制值。我试过的代码如下:

Form.js

<RadioGroup
                    name="callBackSelectionType"
                    initialValues={[
                      {
                        value: CALLBACKREQUIRED,
                        label: "Lower callback limit",
                      },
                      {
                        value: REMOVECALLBACK,
                        label: "Reset to default $10,000",
                      },
                    ]}
                  />
                  {values["callBackSelectionType"] === CALLBACKREQUIRED && (
                    <div className="fields-container">
                      <InputField
                        label={CALLBACK_LIMIT}
                        name="greaterThan"
                        placeholder="$0.00 to $9,999.99"
                        errorMessage={getRequiredMessage(CALLBACK_LIMIT)}
                      />
                    </div>
                  )}

Schema.js

const schema = yup.object().shape({
  callBackSelectionType: yup.string().required(),
  greaterThan: yup.string().when("callBackSelectionType", (val, schema) => {
    if (val === "CALLBACKREQUIRED") {
      return yup
        .number()
        .label(Labels.CALLBACKLIMIT)
        .lessThan(9999.99, "Limit should be less than 9999.99")
        .required(Messages.REQUIRED_FIELD);
    }
    else return yup.string().notRequired();
  }),
});

此验证适用于它是必填字段,但不适用于它应该接受十进制并且应该小于 9999.99 的条件。请帮忙。

提前谢谢你

【问题讨论】:

    标签: reactjs forms validation formik yup


    【解决方案1】:

    您可以尝试使用.max(9999.99, "Commission should not be more than 2 digits") 吗?

    【讨论】:

    • 感谢您的回复。 max 将检查值的长度。对?。我需要的值应该小于 9999.99
    • 对于字符串,它将检查字符串的长度,但对于数字,它将检查数字的值
    • 对于两位数,我将使用自定义验证器方法(避免使用正则表达式,因为我不擅长它们,并且没有它们的验证更简单/更快)。 .test("maxTwoDigits", "Commission should not be more than 2 digits", (number) =&gt; String(number).length &gt;= 3 )
    • return yup .number() .label(Labels.CALLBACKLIMIT) .max(10000, "应该小于 10000") .required(Messages.REQUIRED_FIELD);这不工作,在输入一个大的数字,而不是抛出错误
    猜你喜欢
    • 2020-03-08
    • 2020-12-06
    • 2019-09-29
    • 2019-11-12
    • 2021-12-31
    • 2021-03-10
    • 2021-02-09
    • 2019-09-12
    • 2020-01-01
    相关资源
    最近更新 更多