Yii - 验证

您永远不应该相信从用户那里收到的数据。要使用用户输入验证模型,您应该调用 yii\base\Model::validate() 方法。如果验证成功,它将返回一个布尔值。如果有错误,您可以从 yii\base\Model::$errors 属性中获取它们。

使用规则

要使 validate() 函数工作,您应该覆盖 yii\base\Model::rules() 方法。

步骤 1rules() 方法返回以下格式的数组。

[
    // 必需,指定应验证哪些属性
    ['attr1', 'attr2', ...],
    // 必需,指定规则的类型。
    'type_of_rule',
    // 可选,定义应在哪些场景中应用此规则
    'on' => ['scenario1', 'scenario2', ...],
    // 可选,定义其他配置
    'property' => 'value', ...
]

对于每条规则,您至少应该定义该规则适用于哪些属性以及所应用的规则类型。

核心验证规则是 − boolean、captcha、compare、date、default、double、each、email、exist、file、filter、image、ip、in、integer、match、number、required、safe、string、trim、unique、url。

步骤 2 − 在 models 文件夹中创建一个新模型。

<?php
   namespace app\models;
   use Yii;
   use yii\base\Model;
   class RegistrationForm extends Model {
      public $username;
      public $password;
      public $email;
      public $country;
      public $city;
      public $phone;
      public function rules() {
         return [
            // the username, password, email, country, city, and phone attributes are
            //required
            [['username' ,'password', 'email', 'country', 'city', 'phone'], 'required'],
            // the email attribute should be a valid email address
            ['email', 'email'],
         ];
      }
   }
?>

我们已经声明了注册表单的模型。该模型有五个属性:用户名、密码、电子邮件、国家/地区、城市和电话。它们都是必需的,并且电子邮件属性必须是有效的电子邮件地址。

步骤 3 − 将 actionRegistration 方法添加到 SiteController,我们在其中创建一个新的 RegistrationForm 模型并将其传递给视图。

public function actionRegistration() {
   $model = new RegistrationForm();
   return $this->render('registration', ['model' => $model]);
}

步骤 4 − 为我们的注册表单添加一个视图。在 views/site 文件夹中,使用以下代码创建一个名为 registration.php 的文件。

<?php
   use yii\bootstrap\ActiveForm;
   use yii\bootstrap\Html;
?>

<div class = "row">
   <div class = "col-lg-5">
      <?php $form = ActiveForm::begin(['id' => 'registration-form']); ?>
         <?= $form->field($model, 'username') ?>
         <?= $form->field($model, 'password')->passwordInput() ?>
         <?= $form->field($model, 'email')->input('email') ?>
         <?= $form->field($model, 'country') ?>
         <?= $form->field($model, 'city') ?>
         <?= $form->field($model, 'phone') ?>
         <div class = "form-group">
            <?= Html::submitButton('Submit', ['class' => 'btn btn-primary',
               'name' => 'registration-button']) ?>
         </div>
      <?php ActiveForm::end(); ?>
   </div>
</div>

我们使用 ActiveForm 小部件来显示我们的注册表单。

步骤 5 − 如果您转到本地主机 http://localhost:8080/index.php?r=site/registration 并单击提交按钮,您将看到验证规则正在运行。

验证规则

步骤 6 − 要自定义 username 属性的错误消息,请按以下方式修改 RegistrationFormrules() 方法。

public function rules() {
   return [
      // the username, password, email, country, city, and phone attributes are required
      [['password', 'email', 'country', 'city', 'phone'], 'required'],
      ['username', 'required', 'message' => 'Username is required'],
      // the email attribute should be a valid email address
      ['email', 'email'],
   ];
}

步骤 7 − 转到本地主机 http://localhost:8080/index.php?r=site/registration 并单击提交按钮。您会注意到用户名属性的错误消息已更改。

更改用户名属性

步骤 8 − 要自定义验证过程,您可以覆盖这些方法。

  • yii\base\Model::beforeValidate(): triggers a

    yii\base\Model::EVENT_BEFORE_VALIDATE event.

  • yii\base\Model::afterValidate(): triggers a

    yii\base\Model::EVENT_AFTER_VALIDATE event.

步骤 9 − 要修剪 country 属性周围的空格并将 city 属性的空输入变为空值,您可以使用 trimdefault 验证器。

public function rules() {
   return [
      // the username, password, email, country, city, and phone attributes are required
      [['password', 'email', 'country', 'city', 'phone'], 'required'],
      ['username', 'required', 'message' => 'Username is required'],
      ['country', 'trim'],
      ['city', 'default'],
      // the email attribute should be a valid email address
      ['email', 'email'],
   ];
}

步骤 10 − 如果输入为空,您可以为其设置默认值。

public function rules() {
   return [
      ['city', 'default', 'value' => 'Paris'],
   ];
}

如果 city 属性为空,则将使用默认的"巴黎"值。