Hareesh
Hareesh

Reputation: 1587

How to validate an object with a key inside it in Yup Validation

This is a snippet in my React application using Formik.

My initial value is

initialValues: {
    country: { label: '', value: '' }
}

My field input is country which is a Select option and its value when selected will be as

country: { label: 'India', value: 'India' }

My required error object when a country is not selected should be

{ country: "Please select a country" }

How can I add a yup validation to get my required error when a country is not selected, or in other means when country.value === ''?

I wrote a validation like this

country: yup.object().shape({
        value: yup
            .string()
            .label('Country')
            .required("Please select a country"),
})

which is wrong and this gives the error object as country: { value: "Please select a country" } which is not as my requirement.

What changes should I do here?

Upvotes: 0

Views: 8749

Answers (3)

Misbah Mushtaq
Misbah Mushtaq

Reputation: 1

country: Yup.object()
  .shape({
    label: Yup.string().ensure().required(),
    value: Yup.string().ensure().required(),
  })
  .required("Country cannot be empty")
  .nullable()

In my case, initial value of the country is null, and then it receives an object when the change is triggered.

Upvotes: 0

Hareesh
Hareesh

Reputation: 1587

I found the answer as follows.

country: yup
        .object()
        .test(
          'country', 
          'Please select Country', 
          val => !val.value ? false : true,
        )

This will check if value key inside the country object and return false if empty and the given error will be assigned directly to the country object as required.

Upvotes: 0

Bassem
Bassem

Reputation: 4050

The value: '' is considered a missing value for strings, so most validations besides .required() ignore it. In this case, you can either:

  • Set a default country value
  • Or remove the .required() rule.

Upvotes: 0

Related Questions