【问题标题】:Yii Validation rule for decimal rangeYii 小数范围的验证规则
【发布时间】:2015-12-01 06:37:03
【问题描述】:

我想为小数范围值 40.000 创建一个规则

array('entrance_score', 'compare','operator'=>'<=','compareValue'=>100, 'message'=>'Maximum Entrance Score should be 100.' ),

从 GUI 进行测试时,可以接受小于 100 的十进制数,但不能接受大于或等于 40.000。

以下规则无法正常工作,我该怎么办?

array('entrance_score', 'compare','operator'=>'>=','compareValue'=>0 , 'message'=>'Minimum Entrance Score should be 40.' ),

【问题讨论】:

  • 我在您的第二条规则中看到一个错字,'compareValue'=&gt;0 而不是预期的'compareValue'=&gt;40

标签: php validation yii


【解决方案1】:

那么,您想检查一下entrance_score 的值是否介于40.000100.000 之间,对吗?

您可以在模型中放置 minmax 规则,例如:

array('entrance_score', 'numerical', 'integerOnly'=>false, 'min'=>40, 'max'=>100),

或者,您可以创建自己的自定义验证规则,例如:

public function rules()
    {
        return array(
            //............
            array('entrance_score', 'numerical', 'integerOnly'=>false),
            array('entrance_score', 'authenticate'),
            //.....
        );
    }

还有你的authenticate 函数:

public function authenticate($attribute,$params)
    {
        if($this->entrance_score < 40) {
            $this->addError('entrance_score','Minimum Entrance Score should be 40.');
        } elseif($this->entrance_score > 100) {
            $this->addError('entrance_score','Maximum Entrance Score should be 100.');
        }
    }

应该这样做。

【讨论】:

  • 'integer' 而不是 Yii2 的 'numerical'。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多