简体   繁体   中英

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.

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:

编辑神圣的http-e3y4e

And array.min(limit: number | Ref, message?: string | function) if you want to test length === 0 | 1 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:

编辑happy-sea-dds1e

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM