I can not understand how validators work in YII, here comes the post request to the controller:

public function actionAddnewserver() { if (Yii::$app->request->isAjax) { $data = Yii::$app->request->post(); $server = new Server(); $server->insertNewServer($data); } } 

Before inserting into the database, for example, I want to check $data['url'] for validity. This controller has this method:

 /** * @return array the validation rules. */ public function rules() { return [ // Проверяет, что "website" является корректным URL. Добавляет http:// к атрибуту "website". // если у него нет URI схемы ['website', 'url', 'defaultScheme' => 'http', 'message' => 'ошибка'], ]; } 

This is all I could find from the documentation. How should I understand if the URL correct or not? I work with YII for the first time. Well, logically, I have to pass this string to some boolean method that would return true or false to me, but I don’t understand how to do that.

    1 answer 1

    You need to set the Server model attribute and call the validate () function, which returns true if validation has passed.

     public function actionAddnewserver() { if (Yii::$app->request->isAjax) { $data = Yii::$app->request->post(); $server = new Server(); $server->website = $data['website']; if($server->validate()){ $server->insertNewServer($data); }else{ $errors = $server->errors; } } } 

    Like that. See here Validation Rules for more details.

    • Tell me, should the rules method be in the server model? - Winteriscoming
    • Understood. But I still do not understand. It turns out that the parent class has a method that twitches the rules method and then it already works according to the data in the array? And what if I have in validation not only a web site and, for example, an email, how to understand that the validate method returns true on exactly what I want? - Winteriscoming
    • one
      It will return false if at least one rule fails, i.e. true - if all the rules are executed, the error description will fall into the $ server-> errors variable - Kohl Vasilyev