How can we add a rule in Yii-model for input must be greater than 0

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

like:

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

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

        ....
        ....
    );
}

      

many thanks..

+3


source to share


6 answers


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

using a special validation method



array('SalePrice', 'greaterThanZero')

 public function greaterThanZero($attribute,$params)
   {

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

 }

      

+7


source


I see that this is the price, so you can use 0.01 (pennies) as your minimum value:

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

      



Note that this solution does not confirm that the number entered is a price, namely> 0.01

+2


source


I know that I am too late for this. But just for future reference, you can use this class as well

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


source


Has anyone not checked the documents?

There is a built-in CCompareValidator :

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

      

0


source


you can also use this one:

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

      

0


source


I've handled this with a regex, maybe this will help too ..

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

      

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

-2


source







All Articles