How to add rules using Yii Framework in model?

Micheal Zhang picture Micheal Zhang · Mar 20, 2013 · Viewed 7.4k times · Source

In an web application ,I need to add some rules in the model when create a object. But when I add My rules to the model there are some mistake. For example the mobile number user input when sumit the form.

In view page,there are somew inputs need user to complete ,then I want to add some rules to validate the user input to prevent use input some invalided values.That means using my own validate funcion.

Yours who using Yii Framework,I need Your help,thank you.

Answer

Sudhanshu Saxena picture Sudhanshu Saxena · Mar 20, 2013

EDIT: Using own function in validation rules- In the rule specify the function with attribute like this-

array('username','checkuniquename'),

Then define the function logic in same model Like this:

public function checkuniqueemail($attribute)
{
    $record=Users::model()->findByAttributes(array($attribute=>$this->email));
    if($record!==null)
         $this->addError($attribute, 'This email has been already taken please choose a different one');

}

You can define multiple validation rules on single attribute in Yii models.

return array(
                    array('contact_no','numerical', 'integerOnly'=>true),
                    array('contact_no','length', 'min'=>8 ),
                    array('name, contact_no', 'required'),
        array('name, contact_no', 'length', 'max'=>255),
        array('password','pattern'=>'/^[A-Za-z0-9_!@#$%^&*()+=?.,]+$/u', 'message'=>'Spaces or given characters are not allowed'),
    );

There is lot of validation you can specify in your model.