Hello,
I am trying to create validator for my REST API, and I want to validate some $_GET parameters. My problem is that attributes of my validator model do not get populated with load method, and therefore, validation do not work. Let me show you code example.
Simple validator model:
<?php
namespace app\modules\v1\models\validators;
use yii\base\Model;
/**
* Article validator, responsible for validating parameters for all article based endpoints.
*/
class Article extends Model
{
public $id;
/**
* Returns the validation rules for attributes.
*
* @return array
*/
public function rules()
{
return [
['id', 'required'],
];
}
}
Controller code:
use app\modules\v1\models\validators\Article as ArticleValidator;
public function prepareIndexDataProvider()
{
$validator = new ArticleValidator();
$validator->load(Yii::$app->request->get());
if (!$validator->validate()) {
return $validator->errors;
}
// other code
}
When I send get request without ID parameter to my endpoint I get this error:
{
"id": [
"Id cannot be blank."
]
}
This is OK ( mostly ). I say mostly because this kind of error format is not that nice for web service, but I do not know how to reformat it.
Anyway, when I add ID parameter and send request again, I get the same error message. When I var_dump my validator object after calling load method on it, I can see that id property is null, so I think that load method didn’t actually loaded the value of id to my validator.
Anyone got any clue what may be the problem here ?