Bertho Joris
Bertho Joris

Reputation: 1601

Yii2 Simple Ad Hoc Validation

I create a simple validation like :

public function actionMerchant() {

    $post = Yii::$app->request->post();

    $model = DynamicModel::validateData($post, [
        [['mid'], 'required'],
        [['mid'], 'integer'],
        ['email', 'email'],
    ]);

    if ($model->hasErrors()) {
        return [
            "message" => "Validation fail. Please check your input!"
        ];
    }

    return $model;
}

From the above code, I expect if I send the post parameters for both mid and email parameters, both parameters can be validated by the DynamicModel class.

The problem I get, what if I only send email parameters without mid parameters?

I will get Getting unknown property: yii\\base\\DynamicModel::mid error message.

Does the require validation not work?

Thanks

Upvotes: 0

Views: 422

Answers (1)

Yupik
Yupik

Reputation: 5032

Require validation works fine. Problem is in your DynamicModel, because Yii2 is creating it object attributes from first parameter you pass (for your example thats your $_POST attributes). To make it work correctly, first define model attributes, then load values to it, and then validate.

More in DynamicModel Yii2

=== EDIT ===

$model = new DynamicModel(['mid' => null, 'email' => null]);
$model->addRule('email', 'email');
//here add more rules
$model->load($post);
$model->validate();

Upvotes: 2

Related Questions