Kumara
Kumara

Reputation: 528

yup form validation with conditions react js

I need to validate my field according to radio button value. This is the my sample code for the issue my radio button values are 1st radio button -> values.type === "PO" 2nd radio button -> values.type === "PRE"

this is my validation class,

    import * as Yup from "yup";

const POValidation = Yup.object().shape({
  purchaseOrderNumber: Yup.object()
    .required("This field is Required"),
  amount: Yup.number()
    .required("This field is Required")
    .typeError("Amount is required"),
  number: Yup.string()
    .required("This field is Required"),
  term: Yup.object()
    .required("This field is Required")

});
export { POValidation };

When user select 1st radio button, values.type === "PO", amount field must be mandatory, When user select 2st radio button values.type === "PRE", term field must be mandatory. How I apply this conditions to my validation class? Thanks

Upvotes: 0

Views: 2429

Answers (2)

Viet
Viet

Reputation: 12807

You need add a value to store RadioButton, I call it is radioValue. The you need up date POValidation like this:

...
  amount: Yup.number().when("radioValue", {
    is: (value) => value=== "PO",
    then: Yup.number()
      .required("This field is Required")
      .typeError("Amount is required"),
  }),
  term: Yup.object().when("radioValue", {
    is: (value) => value=== "PRE",
    then: Yup.object().required("This field is Required"),
  }),
...

Upvotes: 1

Renu Yadav
Renu Yadav

Reputation: 149

As per your question you want to add validation on the basis of "type".

Here is the code example you can try:

import * as Yup from "yup";
const POValidation = Yup.object().shape({

type: Yup.string()
      .required("Please select type.")
      .default("default type"),

amount: Yup.number()
      .when("type", {
        is: (isData) => {
          return (
            isData === "PO"
          );
        },
        then: (thendata) => {
          return (
            Yup.number()
              .required("Please select amount.")
              .test({
                message: "Too Short!",
                test: (value) => {
                  return value >= 1;
                },
              })
              .default("default amount")
              .nullable()
          );
        },
      })
      .nullable(),
term: Yup.number()
      .when("type", {
        is: (isData) => {
          return (
            isData === "PRE"
          );
        },
        then: (thendata) => {
          return (
            Yup.number()
              .required("Please select term.")
              .test({
                message: "Too Short!",
                test: (value) => {
                  return value >= 1;
                },
              })
              .default("default term")
              .nullable()
          );
        },
      })
      .nullable()
});
export { POValidation };

Upvotes: 1

Related Questions