yii2.0-rules驗證規則應用實例


Rules驗證規則:

 required : 必須值驗證屬性||CRequiredValidator 的別名, 確保了特性不為空.

[['字段名1','字段名2'],required]    //字段1 2 必填

[['字段名'],required,'requiredValue'=>'必填值','message'=>'提示信息'];

 email : 郵箱驗證||CEmailValidator 的別名,確保了特性的值是一個有效的電郵地址.

['email', 'email'];

 match : 正則驗證||CRegularExpressionValidator 的別名, 確保了特性匹配一個正則表達式.

[['字段名'],'match','pattern'=>'正則表達式','message'=>'提示信息'];      
[['字段名'],'match','not'=>ture,'pattern'=>'正則表達式','message'=>'提示信息'];  /*正則取反*/

 url : 網址||CUrlValidator 的別名, 確保了特性是一個有效的路徑.

['website', 'url', 'defaultScheme' => 'http'];

captcha(驗證碼)||CCaptchaValidator 的別名,確保了特性的值等於 CAPTCHA 顯示出來的驗證碼.

['verificationCode', 'captcha'];

safe : 安全

['description', 'safe'];

compare :(比較) CCompareValidator 的別名, 確保了特性的值等於另一個特性或常量.

['repassword', 'compare', 'compareAttribute' => 'password','message'=>'兩次輸入的密碼不一致!'],

//compareValue:比較常量值 operator:比較操作符 
['age', 'compare', 'compareValue' => 30, 'operator' => '>='];

 default : 默認值||CDefaultValueValidator 的別名, 為特性指派了一個默認值.

['age', 'default', 'value' => null];

 exist : 存在||CExistValidator 的別名, 確保屬性值存在於指定的數據表字段中.

['字段名', 'exist'];

 file : 文件||CFileValidator 的別名, 確保了特性包含了一個上傳文件的名稱.

['primaryImage', 'file', 'extensions' => ['png', 'jpg', 'gif'], 'maxSize' => 1024*1024*1024]

 filter : 濾鏡||CFilterValidator 的別名, 使用一個filter轉換屬性.

//'skipOnArray' => true 非必填
[['username', 'email'], 'filter', 'filter' => 'trim', 'skipOnArray' => true];

 in : 范圍||CRangeValidator 的別名, 確保了特性出現在一個預訂的值列表里.

['level', 'in', 'range' => [1, 2, 3]];

 unique : 唯一性||CUniqueValidator 的別名, 確保了特性在數據表字段中是唯一的.

['字段名', 'unique']

 integer : 整數

['age', 'integer'];

 number : 數字

['salary', 'number'];

double : 雙精度浮點型

['salary', 'double'];

 date : (日期)

[['from', 'to'], 'date'];

 string : 字符串

['username', 'string', 'length' => [4, 24]];

 boolean : 是否為一個布爾值||CBooleanValidator 的別名

['字段名', 'boolean', 'trueValue' => true, 'falseValue' => false, 'strict' => true];

 image :是否為有效的圖片文件

['primaryImage', 'image', 'extensions' => 'png, jpg',  'minWidth' => 100, 'maxWidth' => 1000,  'minHeight' => 100, 'maxHeight' => 1000]

 each:遍歷,ids 和 product_ids 是數字的集合

[['ids', 'product_ids'], 'each', 'rule' => ['integer']],

自定義rules:

['password', 'validatePassword'],

/**
 * Validates the password.
 * This method serves as the inline validation for password.
 *
 * @param string $attribute the attribute currently being validated
 * @param array $params the additional name-value pairs given in the rule
 */
public function validatePassword($attribute, $params)
{
    if (!$this->hasErrors()) {
        $user = $this->getUser();
        if (!$user || !$user->validatePassword($this->password)) {
            $this->addError($attribute, '賬號或者密碼錯誤!');
        }
    }
}

 

來源地址:http://www.yii-china.com/post/detail/9.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM