2

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

5
  • 1
    are you using typescript? Commented Dec 26, 2022 at 10:36
  • no..I am using javascript and reactjs Commented Dec 26, 2022 at 10:36
  • Typescript does this natively. For JS, you will have to write manually Commented Dec 26, 2022 at 10:37
  • Are you using yup ? Commented Dec 26, 2022 at 10:39
  • yes i will be using yup Commented Dec 26, 2022 at 10:40

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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

1 Comment

thanks for your help,is there any way where we can check json has only "name","school" and "address" keys and no other keys

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.