Yii-validation

提供:Dev Guides
移動先:案内検索

Yii-検証

ユーザーから受け取ったデータを決して信頼しないでください。 ユーザー入力でモデルを検証するには、* yii \ base \ Model
validate()メソッドを呼び出す必要があります。 検証が成功した場合、ブール値を返します。 エラーがある場合は、 *yii \ base \ Model :: $ errors プロパティからエラーを取得できます。

ルールを使用する

  • validate()関数を機能させるには、 yii \ base \ Model :: rules()*メソッドをオーバーライドする必要があります。

ステップ1 *- rules()*メソッドは、次の形式で配列を返します。

[
  //required, specifies which attributes should be validated
   ['attr1', 'attr2', ...],
  //required, specifies the type a rule.
   'type_of_rule',
  //optional, defines in which scenario(s) this rule should be applied
   'on' => ['scenario1', 'scenario2', ...],
  //optional, defines additional configurations
   'property' => 'value', ...
]

ルールごとに、少なくともルールが適用される属性と適用されるルールのタイプを定義する必要があります。

コアの検証ルールは、次のとおりです。 、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'],
         ];
      }
   }
?>

登録フォームのモデルを宣言しました。 モデルには、ユーザー名、パスワード、メール、国、都市、電話の5つのプロパティがあります。 これらはすべて必須であり、メールプロパティは有効なメールアドレスである必要があります。

ステップ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 プロパティのエラーメッセージをカスタマイズするには、 RegistrationForm の* rules()*メソッドを次の方法で変更します。

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():トリガー
    + yii \ base \ Model
    EVENT_BEFORE_VALIDATEイベント。
  • yii \ base \ Model :: afterValidate():トリガー
    + yii \ base \ Model
    EVENT_AFTER_VALIDATEイベント。

ステップ9 *-国のプロパティの周りのスペースを切り取り、市のプロパティの空の入力をヌルに変換するには、 *trim および default バリデータを使用します。

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プロパティが空の場合、デフォルトの「パリ」値が使用されます。