Home > Software design >  Validate json with given keys in Javascript and Reactjs
Validate json with given keys in Javascript and Reactjs

Time:12-26

I have below JSON ,

[
 {
  "name":"john",
  "school":"school 2",
  "address":"newyork"
 },
 {
  "name":"peter",
  "school":"school 1",
  "address":"washington"
 }
]

here i want to validate below mentioned things,

1 - it should be an array 2 - it must have only 3 fields (name,school,address) not more that or less than these three fields 3 - "school" can be either 'school1' or 'school2' and "address" can be either "newyork" or "washington"

I amneed to do this using react js and javascript

Thanks in advance

CodePudding user response:

Here is a simplified function of what you are trying to do

const validateJSON = (json) => {
  if (!Array.isArray(json)) {
    return false;
  }
  for (const element of json) {
    if (Object.keys(element).length !== 3) {
      return false;
    }
    if (element.school !== "school 1" && element.school !== "school 2") {
      return false;
    }
    if (element.address !== "newyork" && element.address !== "washington") {
      return false;
    }
  }

  return true;
};

then just use const isValid = validateJSON(json);

CodePudding user response:

Validation using yup

const schema = yup.array()
    .of(
      yup.object().shape({
        name: yup.string().required("Required"),
        school: yup.mixed().oneOf(['school 1','school 2']),
        address: yup.mixed().oneOf(['newyork','washington'])
      }).noUnknown(true)
    )

and validate,

await schema.validate(your_object).catch(function (err) {
  err.name; // => 'ValidationError'
  err.errors;
});

Note: this validation is not tested

  • Related