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:
Index.php
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');
}
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…)