1

I have created a form with some entities (say name,address,etc.). And I have defined validation rules in model class. Client side validation is working perfectly as desired. Now I need to create custom validation rules. For that,in reference with http://www.yiiframework.com/wiki/168/create-your-own-validation-rule/#hh0 , I have created a method called valid_number() in my model, and defined a simple null checking (I know there are built in rules for validating null,email,password, etc.. Here I have demonstrated a simple method of validation, actually I'm planning to do some custom validations). Please refer the code below. And please let me know what I am doing wrong.

//model

class Employee extends CActiveRecord{
  public $number;
  public function rules(){
     return array(
                  array('number','valid_number'),
                  );
  }


 public function valid_number($attribute,$params){
    if($this->$attribute == '' ){
         CModel::addError($attribute, 'Number is null');
    }
   }

//view

</fieldset>
   <?php echo $form->textFieldRow($model, 'number'); ?>
</fieldset>
2
  • What is the error? the model is validated whitout any error, a php error happened? Commented Jan 23, 2013 at 9:21
  • So what exactly happens? Is your method called? What does var_dump($this->$attribute) output? Commented Jan 23, 2013 at 10:34

3 Answers 3

3

CModel::addError should be $this->addError.

Sign up to request clarification or add additional context in comments.

2 Comments

'Didn't work' doesn't work, whats the output? whats the error? what info do you have from a debug attempt?
@Pradeep You should call CFormModel::error function to display number attribute errors. like this: <?php echo $form->error($model, 'number'); ?> and if just validate attribute is empty, you maybe can try required validator
0
<?php 
$this->addError($attribute, 'Your error message');
?>

Comments

0

Why are you calling the static function CModel::addError?

You could just call addError of the object and it works:

public function valid_number($attribute, $params) {
    if ($this->$attribute == '' ) {
        $this->addError($attribute, 'Number is null');
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.