Бортовой журнал Ктулху

Yii2 custom validation in model

That is how can we make a custom validation for field `Password` in Yii2. For example, the password must contain at least 1 uppercase letter, 1 lowercase letter, and 1 digit, with a length ranging from 8 to 32 characters.

It's not too hard. Just create method validateCustomPassword() in model.

 

 

public function rules()
 {
 return [
 ['Pass','string', 'min' => 8,'max' => 32],
 ['Pass', 'validateCustomPassword'],
];
 }
 
public function validateCustomPassword($attribute, $params)
 {
 if($attribute === 'Pass') {
 if (!preg_match('/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,}$/', $this->Pass)) {
 $this->addError($attribute, 'Error text');
 }
 }
 }