question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

How to validate an array of objects?

See original GitHub issue

I have a JSON object which contains an array of JSON objects. My need is out of 2 array elements (vehicles), I just need to ensure that at least one is filled with data i.e. both can’t be empty… see my declaration below and my Yum schema

const initialValues = {
  applicantID: "",
  applicantTypeID: "1",
  firstName: "",
  lastName: "",
  email: "user@abc.com",
  address1: "",
  address2: "",
  suburb: "",
  state: "NSW",
  postcode: "",
  phone: "",
  mobile: "",
  business_unit_school: "",
  building: "",
  level: "",
  room: "",
  applicationStatusID: "1",
  vehicles: [
    { registrationNumber: "", make: "", model: "" },
    { registrationNumber: "", make: "", model: "" },
  ],
};

const validationSchema = Yup.object({
  applicantID: Yup.string().required("Employee Number required."),
  firstName: Yup.string()
    .min(2, "Too Short!")
    .max(30, "Max 30 characters allowed.")
    .required("Firstname required."),
  lastName: Yup.string()
    .min(2, "Too Short!")
    .max(30, "Max 30 characters allowed.")
    .required("Lastname required."),
  email: Yup.string().email("Invalid email format").required("Email required."),
  address1: Yup.string()
    .min(2, "Too short.")
    .max(255, "Too Long!")
    .required("Address required."),
  address2: Yup.string().max(255, "Max 255 characters allowed."),
  suburb: Yup.string()
    .min(2, "Too Short!")
    .max(30, "Max 30 characters allowed.")
    .required("Suburb required."),
  state: Yup.string()
    .min(2, "Too Short!")
    .max(30, "Max 30 characters allowed.")
    .required("State required."),
  business_unit_school: Yup.string()
    .min(2, "Too Short!")
    .max(100, "Max 100 characters allowed.")
    .required("Business unitschool required."),
  vehicles: Yup.array().of(
    Yup.object().shape({
      registrationNumber: Yup.string().required("Required"),
    })
  ),
postcode: Yup.string().required("Postcode required."),
  phone: Yup.number()
    .required("Phone number required")
    .typeError("You must specify a number"),
  mobile: Yup.number().required("").typeError("You must specify a number"),
});

My above vehicles validation works though it forces user to fill in registrationNumber element of both array items under vehicle which is not I want. Any help would be much appreciated. I also tried below and it doesn’t work …

let vehicleschema = Yup.object({
  vehicles: Yup.array().of(
    Yup.object({
      registrationNumber: Yup.string().required("Required"),
      make: Yup.string().required("Required"),
    })
  ),
});

const validationSchema = Yup.object({
vehicles: vehicleschema.validateAt("vehicles[0].registrationNumber", initialValues)
}),

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Comments:9

github_iconTop GitHub Comments

9reactions
DewangScommented, Aug 25, 2020

No help from the community though managed to solve it on StackOverflow. Disappointing support for such a great library.

4reactions
DewangScommented, Aug 25, 2020

ok, now to begin with, while Yup is a great library and solves many pressing JS validation issues, the lack of support for such queries is equally disappointing. I could clearly see many other questions answered after I posted mine and no one bothered to even ack this query. Finally I managed to solve this by getting help on StackOverflow as Yup doesn’t provide this sort of validation out of box i.e. when you want to conditionally validate one or more element within an array of JSON objects

here is the link to the SO query and the final solution …

https://stackoverflow.com/questions/63534689/how-to-validate-individual-element-of-an-array-of-json-objects-using-yup

I wish Yup documentation gets some improvements with examples as it is not very clear as it is. Is there a book on Yup?

Read more comments on GitHub >

github_iconTop Results From Across the Web

How to validate objects in Array - javascript - Stack Overflow
You can do this by writing a validation function using Array's filter function: const isValid = objects => { return objects.filter(el ...
Read more >
Validating an array of objects - Laracasts
Use array_filter . Copy Code $validItems = array_filter($recipients, function($item){ return ...
Read more >
Use .every() to Validate JavaScript Array Values
If your task at hand is to validate all elements in an array, then you need to be using the every() method.
Read more >
Validating a JavaScript Array | Kevin Chisholm - Blog
Validating a JavaScript Array · // example # 1: check if the length property of the passed-in array is 0 · // example...
Read more >
How to Validate an Array of Objects in Laravel - Black Deer Dev
To validate an array of objects in Laravel, you can use the * identifier for each item in an array, and use the...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found