Home > Net >  React Formik Yup validation for checking input value less than a number
React Formik Yup validation for checking input value less than a number

Time:12-30

I have one form built using Formik. There are two radio buttons in the form, when clicking one radio button an input field will appear. I need to validate that input field with Yup validation. The value should be less than 9999.99 and it may accept both integer and decimal values also. The code I tried is given below:

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();
  }),
});

This validation works for that it is required field, but not working for the condition that it should be accept decimal and should be less than 9999.99. Please help .

Thank you in advance

CodePudding user response:

Can you try to use .max(9999.99, "Commission should not be more than 2 digits") ?

  • Related