我们如何在Yii模型中为输入添加规则必须大于0

时间:2012-03-29 06:45:20

标签: validation yii model yii-validation

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

喜欢:

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

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

        ....
        ....
    );
}
非常感谢..

6 个答案:

答案 0 :(得分:7)

更简单的方法 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');

 }

答案 1 :(得分:2)

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

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

请注意,此解决方案不会验证输入的数字是否为价格,只是它是&gt; 0.01

答案 2 :(得分: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').");
 }";
}

 }

?>

请确保在使用前导入此类。

答案 3 :(得分:0)

没人检查文档吗?

内置验证器CCompareValidator

<html>
   <head>
      <head>
   </head>
   <body>
      <a href="psr:start">Start Recording</a>
   </body>
   </head>
</html>

答案 4 :(得分:0)

你也可以使用这个:

array('SalePrice', 'in','range'=>range(0,90))

答案 5 :(得分:-2)

我通过正则表达式来处理这个问题,也可能会有所帮助..

array('SalePrice', 'match', 'not' => false, 'pattern' => '/[^a-zA-Z0]/', 'message' => 'Please enter a Leader Name', "on"=>"sale"),
非常感谢@sdjuan&amp; @Ors为您提供帮助和时间..