Yii2: how to use custom validation function for activeform?

前端 未结 12 1275
独厮守ぢ
独厮守ぢ 2020-12-25 14:18

In my form\'s model, I have a custom validation function for a field defined in this way

class SignupForm extends Model
{
    public function rules()
    {
          


        
12条回答
  •  天涯浪人
    2020-12-25 14:31

    To make custom validations in yii 2 , you can write custom function in model and assign that function in rule. for eg. I have to apply password criteria in password field then I will write like this in model.

    public function rules()
    {
        return [
            ['new_password','passwordCriteria'],
        ];
    }
    
    public function passwordCriteria()
    {
        if(!empty($this->new_password)){
            if(strlen($this->new_password)<8){
                $this->addError('new_password','Password must contains eight letters one digit and one character.');
            }
            else{
                if(!preg_match('/[0-9]/',$this->new_password)){
                    $this->addError('new_password','Password must contain one digit.');
                }
                if(!preg_match('/[a-zA-Z]/', $this->new_password)){
                    $this->addError('new_password','Password must contain one character.');
                }
            }
        }
    }
    

提交回复
热议问题