how we can add rule in Yii model for input must be greater than 0

21.2k views Asked by At

do anyone know how can I apply rule in Yii model for input must be greater than 0 value, without any custom approach ..

like :

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

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

        ....
        ....
    );
}

many thanks ..

6

There are 6 answers

3
adamors On BEST ANSWER

Simpler way array('SalePrice', 'numerical', 'min'=>1)

with a custom validator method

array('SalePrice', 'greaterThanZero')

 public function greaterThanZero($attribute,$params)
   {

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

 }
0
alwaysLearn On

I know I am too late for this . But just for future reference you can use this class also

<?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').");
 }";
}

 }

?>

Just make sure this class is imported before use.

0
Ebrahim Poursadeqi On

you can use this one too:

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

I see it is a price so you could use 0.01 (a penny) as a minimum value like so:

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

Note that this solution does not validate that the number entered is a price, just that it is > 0.01

0
Shadman On

I handled this by regular expression, may be it will help too ..

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

many thanks @sdjuan & @Ors for your help and time ..

0
Arth On

Did nobody check the docs?

There is a built-in validator CCompareValidator:

['SalePrice', 'compare', 'operator'=>'>', 'compareValue'=>0]