skip to Main Content

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

2

Answers


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

    Login or Signup to reply.
  2. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search