简体   繁体   中英

How to add rules using Yii Framework in model?

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.

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.

First you need to specify a validation rule in your model like

return array(
.......    
array('duration', 'days_available'),
.....

);

where duration is the field name and days_available will be the function name. Then you need to write the function within the model.

public function days_available($attribute,$params)
{
  //provide proper condition
  $this->addError('duration','validation message');
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM