YII2 validation check unique between two fields without using active record

China☆狼群 提交于 2019-12-10 12:24:34

问题


I am using two fields "old_password" and "new_password". I want the error message if value in both fields are same. I am not using Activerecords. I tried in model :

['a1', 'unique', 'targetAttribute' => 'a2']

but above code will work only for active record. How can i get error message without using active record ?


回答1:


You need to use compare validator instead of unique.

['new_password', 'compare', 'compareAttribute' => 'old_password', 'operator' => '!='],

Because unique validator validates that the attribute value is unique across the table




回答2:


If your model extend yii\base\Model, activeRecerd are not necessary and you can use the rules function

public function rules()
{
    return [ 
      ['a1', 'unique', 'targetAttribute' => 'a2'],
    ];

}

for assign your validation rules

and in your controller you can perform validation invoking $model->validation

$model = new \app\models\YourForm();

like suggested in Yii2 guide for validating input

// populate model attributes with user inputs
$model->load(\Yii::$app->request->post());
// which is equivalent to the following:
// $model->attributes = \Yii::$app->request->post('ContactForm');

if ($model->validate()) {
    // all inputs are valid
 } else {
   // validation failed: $errors is an array containing error messages
  $errors = $model->errors;
}


来源:https://stackoverflow.com/questions/34794192/yii2-validation-check-unique-between-two-fields-without-using-active-record

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!