yii自定义验证

 

  • 自定义验证类
    class BaseModel extends Model {
      public function rules() {
            return [
                ['obj', ContentSecurityValidator::class],
            ];
        }
      public function exec() {
            if (!$this->validate()) {
                return [
                    'errors' => $this->errors
                ];
            }
       }
      public function attributeLabels() {
            return [
                'obj' => '标签',
            ];
        }
    }
    
    /**
    * 自定义验证类
    */
    class BaseValidator extends Validator {
    
         /**
         * 必须要实现该方法
         * @param \yii\base\Model $model
         * @param string $attribute 参数名
         * @return bool
         */
        public function validateAttribute($model, $attribute) {
            $attributeValue = $model->$attribute;//获取$model里面的参数的值
            $attributes = $model->attributes;//获取model里面的参数数组
            $attributeLabels = $model->attributeLabels();//获取model里面的已经设置好参数对应标签
            
        }
    }

     

  • 自定义验证方法
    class BaseModel extends Model {
      public function rules() {
            return [
                ['obj', 'validate'],
            ];
        }
      public function exec() {
            if (!$this->validate()) {
                return [
                    'errors' => $this->errors
                ];
            }
       }
      public function attributeLabels() {
            return [
                'obj' => '标签',
            ];
        }
      /**
       * 自定义方法
       */
      public function validate($attribute) {
            $attributeValue = $this->$attribute;//获取$model里面的参数的值
            $attributes = $this->attributes;//获取model里面的参数数组
            $attributeLabels = $this->attributeLabels();//获取model里面的已经设置好参数对应标签
            
        }
    }
    
        

     

  • 不刷新,通过切换select的按钮,面对不同场景时,设置某些必填项
    public function rules() {
            return [
                [['email', 'phone'], "requiredValidators", 'skipOnEmpty' => false, 'skipOnError' => false],
            ];
        }
    
        public function requiredValidators($attribute) {
            if ($this->typeId == 'register') {
                $isAttrEmpty = !$this->$attribute || empty($this->$attribute) || $this->$attribute === '' || $this->$attribute == null;
                if ($isAttrEmpty)
                    $this->addError($attribute, $this->attributeLabels()[$attribute] . '不能为空');
            }
        }
    
        public function attributeLabels() {
            return [
                'email'=>'邮箱',
                'phone'=>'手机'
            ]
        }            

     

 

posted @ 2019-09-06 15:23  好胖的兔子  阅读(349)  评论(0编辑  收藏  举报