问题
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