简体   繁体   中英

Validate json with given keys in Javascript and Reactjs

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

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);

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

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