0

Actually I'm working on ajax validation in Yii 2. I am sending two public variables data into a column in DB. while loading a post values. How to validate custom onto that field.

My Code:

public $prefix;
public $mobile;
$model->phone = Yii::$app->request->post('prefix') . '' . Yii::$app->request->post('mobile');

and I want this

['phone, 'unique']

Thanks in advance

tereško
  • 58,060
  • 25
  • 98
  • 150
rehan
  • 13
  • 4
  • Code which you pasted is not enough, it's just uncategorized scraps. Paste here full controller/model code, otherwise we can't help you. – Yupik Aug 11 '17 at 07:55

2 Answers2

0

Add the rule to the class definition of the model, validate and do with the validation result what you want. E.g. return true when validated true or the error message when validated false.

class YourModel extends ActiveRecord {
    public function rules()
    {
        return [
            ['phone', 'unique'],
        ];
    }
}

$model->validate();

If you have more validation rules you can get the result for the phone attribute using $model->getErrors('phone').

Barry
  • 3,683
  • 1
  • 18
  • 25
0

You need to merge both variables before calling validate function on model. Your controller action code should be like below :

$model->phone=model->prefix.$model->mobile;
$model->validate();
//rest of code