2018-11-06 22:35:21 1449次浏览 2条回答 0 悬赏 20 金钱

场景的验证规则

['state', 'required', 'when' => function ($model) {
        return $model->country == 'USA';
    }, 'whenClient' => "function (attribute, value) {
        return $('#country').value == 'USA';
    }"],

这个能写自定函数在里面吗。还是只能判断 真 假

'when'=>function($model){



}
还有
 yii\base\Model::addError(name’,‘错误内容’) ;
 怎么打印不出类似 name:['错误内容']   
 
直接就一个空白页面给我

最佳答案

  • 小叮当的肚兜 发布于 2018-11-06 23:10 举报
    if ($this->when === null || call_user_func($this->when, $model, $attribute)) {
        $this->validateAttribute($model, $attribute);
    }
    

    看样子是只能判断真假了

    1 条回复
    回复于 2018-11-06 23:17 回复

    郁闷了了了

  • 回答于 2018-11-06 23:48 举报

    yii\validators\Validate的源码,应该是可以的

    public function validateAttributes($model, $attributes = null)
        {
            if (is_array($attributes)) {
                $newAttributes = [];
                $attributeNames = $this->getAttributeNames();
                foreach ($attributes as $attribute) {
                    if (in_array($attribute, $attributeNames, true)) {
                        $newAttributes[] = $attribute;
                    }
                }
                $attributes = $newAttributes;
            } else {
                $attributes = $this->getAttributeNames();
            }
    
            foreach ($attributes as $attribute) {
                $skip = $this->skipOnError && $model->hasErrors($attribute)
                    || $this->skipOnEmpty && $this->isEmpty($model->$attribute);
                if (!$skip) {
                    if ($this->when === null || call_user_func($this->when, $model, $attribute)) {
                        $this->validateAttribute($model, $attribute);
                    }
                }
            }
        }
    
    4 条回复
    回复于 2018-11-07 00:09 回复
    'state', 'required', 'when' => function ($model) {
            return $model->country == 'USA';
        }】
    
    
    不是
    
    【'state', 'validateAttributes',】
    
    回复于 2018-11-07 00:11 回复
    'name', 'unique', 'when' => function () {
            //查找账号是否存在,的函数
        }】```
    
    我是想这样来的
    
    回复于 2018-11-07 00:14 回复

    ['name','unique','targetAttribute' => 'name', 'message' => '账号已存在'],
    直接这样写的话,好像不能灵活查询其他库的账号吧,
    所以想用

    ['name', 'unique', 'when' => function () {
            //查找账号是否存在,的函数
        }]
    

    可惜好像只能判断真假,不能当函数用

    回复于 2018-11-07 09:32 回复

    已经解决了。继承父类把父类的find方法,getdb方法重写了

您需要登录后才可以回答。登录 | 立即注册
开门_查水表
助理

开门_查水表

注册时间:2018-09-28
最后登录:2018-11-14
在线时长:6小时2分
  • 粉丝0
  • 金钱115
  • 威望0
  • 积分175

热门问题