Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validation using Yup to check array length --> error if length === 1

I have the following object:

{
    array: [1]
}

And the following code:

myArray: Yup.array().of(
    Yup.object().shape({
        name: Yup.string().max(255).required().label('Name')
    })
)

Now I check the name is required, I need to check if myArray has length === 1 to return an error.

like image 635
Mauro SkyDancer Donadel Avatar asked Jun 02 '20 09:06

Mauro SkyDancer Donadel


1 Answers

You could use mixed.test(options: object) if you would just like to test length === 1:

myArray: array()
  .of(
    object().shape({
      name: string()
        .max(255)
        .required()
        .label("Name")
    })
  )
  .test({
    message: 'The error message if length === 1',
    test: arr => arr.length !== 1,
  })

Demo:

Edit holy-http-e3y4e

And array.min(limit: number | Ref, message?: string | function) if you want to test length === 0 | 1 :

myArray: Yup.array()
  .of(
    Yup.object().shape({
      name:Yup.string()
        .max(255)
        .required()
        .label('Name')
      })
  )
  .min(2, 'The error message if length === 0 | 1')

Demo:

Edit happy-sea-dds1e

like image 91
Fraction Avatar answered Nov 10 '22 20:11

Fraction