Creating Custom Validation Rule In Model

Hi All,

I am trying to create a custom validation rule to check if a card number is greater than zero. But it doesnt seem to work. Below is my code:


public function rules() {

        return array(

            array('cardNumber', 'greaterThanZero'),



public function greaterThanZero($attribute, $params) {

        if ($this->$attribute <= 0)

            $this->addError($attribute, 'Number has to be greater than 0');


Please let me know what wrong am i doing here

try this

if ($this->$cardNumber<= 0)

            $this->addError($attribute, 'Number has to be greater than 0');


Thanks a lot for it. But it still doesnt seem to work for me.

I actually have a form created from the model data and when the form is submitted i want to apply these validation rules.

I noticed that your post says index.php… If your code is in the model that defines cardNumber, it should work.

However, there might be a casting problem if cardNumber is a non-numeric field. (Any string that doesn’t start with a zero is casted to 1 and therefore > 0.)

Hint: if you change your condition to "if(true)", you can test if the rule is used at all during validation.

I you can’t figure it out, give us more information (e.g. how did you test it, what was the result, what code is in the controller action…)

please see this

I hope it’s some help