Home > Software engineering >  Is there to validate json objects with another array of json in php
Is there to validate json objects with another array of json in php

Time:06-25

Please I have a form parameter as follows. I am try to build a dynamic form based on the schema below. In my database, I have a table column which is json. I am trying to guide against entering anyhow data except those ones defined in the form array of objects

formDefinition = [
          {
            "key": "name",
            "value": "",
            "datatype": "string"
           },
           {
            "key": "sex",
            "value": " ",
            "datatype": "choice"
           },
           {
            "key": "occupation",
            "value": "",
            "datatype": "string"
           },
           {
            "key": "isRetired",
            "value": ,
            "datatype": "boolean"
           }
        ]

Table: employee and field name is details which is a json type.

details = [{}]

When the user fills the form and on submission, it would look as follows.

details = [{"name": "something something"}, {"sex": "male"}, {"occupation": "something" }]

I need some of validation check to see if the details has the same keys as it is defined in the form otherwise it should throw error.

I haven't tried this code as I am not sure if it is possible. Just to illustrate what I am trying to achieve.

public function dataValidator($data)
{
  foreach($data as $key => $value){
    foreach(formDefinition as form){
       if($key !== form['key']){
          return "invalid"
        }
     }
  }
}

CodePudding user response:

Doesn't look that bad. However, only one loop is required:

public function dataValidator($data)
{
    foreach($data as $key => $value) {
        $valid = current(array_filter($formDefinition, function($form) use($key) { return $form->key === $key; }));
        if(!$valid) {
            return 'invalid';
        }
    }
}

Short tip for next time: Just try it out. That might avoid unnecessary questions since you might already get the answers from the result. And if not, you at least have sufficient debugging information to share with us ;-)

  • Related