Yii2: Why yii2 dont have json validation on rules on models?

Created on 4 Apr 2016  路  11Comments  路  Source: yiisoft/yii2

I work more time on validate a json field when i work with REST APIs, because more time user dont send required fields on json, Yii2 can add a json validation rule on models and a parser for check exist fields on a json Object or Array, For sample:

[
 {
     "lat": 32.981233,
     "lng":-122.82488
 },
 {
     "lat": 32.981212,
     "lng":-122.82348
 },
 {
    "lat":32.657232
 }
]

This Json Array have two required field on each object(lat, lng), we can set a schema on rule to check to exist required fields with config a deep, For sample:

 public function rules()
    {
        return [
            // These field are required on json array 
            [location', 'json','DEEP', [// LIST OF REQUIRED FIELDS WITH FILED TYPES(STRING, INTEGER, etc ...) HERE AS ARRAY KEY]],
        ];
    }

Also i know about Json parser config for this goal, I mean we need to generate a new validator.

'request' => [
    'parsers' => [
        'application/json' => 'yii\web\JsonParser',
    ]
]

Do you have any idea Team?
If it's good looks, Can i add a contributors to help develop this feature?

Additional info

| Q | A |
| --- | --- |
| Yii version | 2 |

enhancement

Most helpful comment

I don't know. Personally I'm avoiding input in form of un-parsed JSON structures. I prefer to parse it, fill a model (or models) from it and then validate. That's much cleaner.

All 11 comments

Thank you for your idea.
Indeed, currently we do not have any kind of core validators for JSON strings.

You can reach the goal using FilterValidator and DynamicModel. Something like

    public function rules()
    {
        return [
            [['location'], 'filter', 'filter' => function ($value) {
                try {
                    $result = [];

                    $data = \yii\helpers\Json::decode($value);
                    $dynamicModel = (new \yii\base\DynamicModel())->addRule(['lat', 'lng'], 'required');
                    foreach ($data as $item) {
                        $itemModel = $dynamicModel->validateData($item);
                        if ($itemModel->hasErrors()) {
                            $this->addError('location', reset($itemModel->getFirstErrors()));
                            return null;
                        }
                    }

                    return $value;
                } catch (\yii\base\InvalidParamException $e) {
                    $this->addError('location', $e->getMessage());
                    return null;
                }
            }],
        ];
    }

(the code is not tested, it only shows the idea)

However is not suitable for multi-dimensional arrays, because the rule will be too huge, hard to read and understand. What API do you suggest for JSON validator?

@SilverFire Thanks, It's very amazing, I don't have any idea API for suggestion, But your current code can be embed to core validation rules, Today Yii2 use for develop REST APIs or JQuery or Angular sites and json validation is very important.

Maybe, it's even better to create a real model, that represents each JSON array item. Then you can store validation rules in it and make main model's code clearer.

But anyway I'd like to have an easier way to do same. Just don't have a good design idea...

I'll try to find a good idea and let know when i find a optimized solution ... Please just keep open this issue until 2 days...
Thanks anyway.

No problem. Thank you for participation and effort!

Use json_decode() to parse JSON and verify it is correct. It will return NULL if there is an error.

http://php.net/manual/en/function.json-decode.php

@SilverFire Can you check please these ideas and let me know if you had better idea:
https://github.com/justinrainbow/json-schema
https://github.com/ptrofimov/matchmaker

I think these libraries get good idea before design a model rule on Yii2.
Thanks

Laravel has a good idea as well https://laravel.com/docs/5.2/validation#validating-arrays

@SilverFire :+1: Just let me know how to Yii team think about this feature?
@samdark @qiangxue Do you have any idea? Do we need to this feature on Yii2 or No?
More than of Yii2 developers have this problem really and When we work with REST APIs or Ajax call its very important to check JSON requests.

I don't know. Personally I'm avoiding input in form of un-parsed JSON structures. I prefer to parse it, fill a model (or models) from it and then validate. That's much cleaner.

Analyzing likes I make a conclusion that JSON schema validation is not required in model.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

schmunk42 picture schmunk42  路  47Comments

AstRonin picture AstRonin  路  49Comments

alexandernst picture alexandernst  路  163Comments

Faryshta picture Faryshta  路  48Comments

rosancoderian picture rosancoderian  路  46Comments