Question

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 ..

Was it helpful?

Solution

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');

 }

OTHER TIPS

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

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.

Did nobody check the docs?

There is a built-in validator CCompareValidator:

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

you can use this one too:

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

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 ..

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top