4

有谁知道我如何在 Yii 模型中应用规则输入必须大于 0 值,没有任何自定义方法..

像 :

public function rules()
{
    return array( 
        ....
        ....

            array('SalePrice', 'required', "on"=>"sale"),

        ....
        ....
    );
}

非常感谢 ..

4

6 回答 6

8

更简单的方法 array('SalePrice', 'numerical', 'min'=>1)

使用自定义验证器方法

array('SalePrice', 'greaterThanZero')

 public function greaterThanZero($attribute,$params)
   {

      if ($this->$attribute<=0)
         $this->addError($attribute, 'Saleprice has to be greater than 0');

 }
于 2012-03-29T07:46:15.893 回答
2

我认为这是一个价格,因此您可以使用 0.01(一美分)作为最小值,如下所示:

array('SalesPrice', 'numerical', 'min'=>0.01),

请注意,此解决方案不验证输入的数字是价格,只是验证它 > 0.01

于 2012-03-29T07:43:57.737 回答
0

我知道我为时已晚。但仅供将来参考,您也可以使用此类

<?php
class greaterThanZero extends CValidator 
{
/**
 * Validates the attribute of the object.
 * If there is any error, the error message is added to the object.
 * @param CModel $object the object being validated
 * @param string $attribute the attribute being validated
*/
 protected function validateAttribute($object,$attribute)
  {
    $value=$object->$attribute;
     if($value <= 0)
    {
    $this->addError($object,$attribute,'your password is too weak!');
}
 }


  /**
  * Returns the JavaScript needed for performing client-side validation.
  * @param CModel $object the data object being validated
  * @param string $attribute the name of the attribute to be validated.
   * @return string the client-side validation script.
  * @see CActiveForm::enableClientValidation
*/
 public function clientValidateAttribute($object,$attribute)
 {

    $condition="value<=0";
     return "
   if(".$condition.") {  messages.push(".CJSON::encode($object->getAttributeLabel($attribute).' should be greater than 0').");
 }";
}

 }

?>

只需确保在使用前导入此类。

于 2013-12-20T07:16:06.393 回答
0

没有人检查文档吗?

有一个内置的验证器CCompareValidator

['SalePrice', 'compare', 'operator'=>'>', 'compareValue'=>0]
于 2015-05-07T14:41:12.883 回答
0

你也可以使用这个:

array('SalePrice', 'in','range'=>range(0,90))
于 2015-06-08T21:55:28.457 回答
-2

我通过正则表达式处理了这个,可能它也会有帮助..

array('SalePrice', 'match', 'not' => false, 'pattern' => '/[^a-zA-Z0]/', 'message' => 'Please enter a Leader Name', "on"=>"sale"),

非常感谢@sdjuan 和@Ors 的帮助和时间..

于 2012-03-30T05:55:33.350 回答