最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Yup validation -- making sure an array contains at least one item - Stack Overflow

programmeradmin4浏览0评论

I have an array like this

{
    array: ["1", "4"]
}

but I want to add a yup validation to it -- if the array is empty - so at least one item is in the array

I've tried something like this - but its not working

myArray: yup.array().min(1). required("at least one item needs to be here")

are empty arrays always truthy? Yup: Validating Array of Strings That Can Be Empty

but this sandbox seems to work? =/src/index.js


here is the formik formframe work - with checkboxes -- shown - but when the checkboxes are not selected aka value is an empty array -- the error should show - but it doesnt?

I have an array like this

{
    array: ["1", "4"]
}

but I want to add a yup validation to it -- if the array is empty - so at least one item is in the array

I've tried something like this - but its not working

myArray: yup.array().min(1). required("at least one item needs to be here")

are empty arrays always truthy? Yup: Validating Array of Strings That Can Be Empty

but this sandbox seems to work? https://codesandbox.io/s/serene-khorana-3pjmq?file=/src/index.js


https://codesandbox.io/s/lively-rgb-b2sct

here is the formik formframe work - with checkboxes -- shown - but when the checkboxes are not selected aka value is an empty array -- the error should show - but it doesnt?

Share Improve this question edited May 28, 2021 at 11:53 The Old County asked May 27, 2021 at 23:23 The Old CountyThe Old County 8914 gold badges67 silver badges141 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 15

What you did is already correct and expected. I'm not sure what's your confusion.

If the code is:

import "./styles.css";
//import { object, array } from "yup";
import * as yup from "yup";

const mySchema = yup.object({
  myArray: yup.array().min(1, "at least 1").required("required")
});

console.log("[]", mySchema.isValidSync({ myArray: [] }));

console.log(
  '["John"]',
  mySchema.isValidSync({
    myArray: ["John"]
  })
);

console.log(
  '["John", "Doe"]',
  mySchema.isValidSync({
    myArray: ["John", "Doe"]
  })
);

It returns:


[] false
["John"] true
["John", "Doe"] true

If I changed the line to myArray: yup.array().min(2, "at least 2").required("required")

Then it returns:

[] false
["John"] false
["John", "Doe"] true
发布评论

评论列表(0)

  1. 暂无评论