Rules and validation in Yii Model

This tutorial will help you to understand the yii model rules, user defined functions. In yii rules function I added code (of yiiframework) for unique,email,password comparison, date, phone number, trim etc.. I created user functions for alphanumeric password validation, phone number or mobile number requirements validation.

Default Validation

This will work only the target values is empty or null.

array('created_on', 'default',
        'value'=>new CDbExpression('NOW()'), 
        'on'=>'insert'),
In this code, i added one parameter 'setOnEmpty'.whether to set the default value only when the attribute value is null or empty string.

Update Every Time


array('updated_on', 'default',
        'value'=>new CDbExpression('NOW()'),		
        'setOnEmpty'=>false, 
        'on'=>'insert'),

Update First Time


array('updated_on', 'default',
        'value'=>new CDbExpression('NOW()'),		
        'setOnEmpty'=>true, 
        'on'=>'insert'),

Compare Validation


//password comparison
array('password', 'compare', 'compareAttribute'=>'password'),
                        
//From date and To date comparison
// Using Oprerator
array(
    'last_date',
    'compare',
    'compareAttribute'=>'start_date',
    'operator'=>'>', 
    'allowEmpty'=>false , 
    'message'=>'{attribute} must be greater than "{compareValue}".'
),                        

Date/Time Validation


//Date
array('dob', 'type',
            'type' =>'date',
            'message' => '{attribute}: is not a date!', 
            'dateFormat' => 'yyyy-MM-dd'),
//Time
array('birthtime', 'type', 
            'type'=>'time',
            'timeFormat'=>'hh:mm'),
                   
array('datetime', 'type', 
            'type'=>'datetime',
            'timeFormat'=>'MM/dd/yyyy hh:mm'),

Email Validation


array('emailid', 'email'),

File Validation


array('userimage', 'file', 
            'allowEmpty'=>true, 
            'types'=>'jpg, gif, png', 
            'on'=>'insert',//scenario
            'except'=>'update',
            'message' => 'Upload Valid Image!',  // Error message
            'wrongType'=>'File type is Invalid',
            'minSize'=>1024,// 1MB
            'maxSize'=>1024,
            'maxFiles'=>4,
            'tooLarge'=>'File Size Too Large',//Error Message
            'tooSmall'=>'File Size Too Small',//Error Message
            'tooMany'=>'Too Many Files Uploaded',//Error Message                                
    ),  

Integer Validation


array('status', 'numerical', 'integerOnly'=>true),

Minimum Length Validation


array('username', 'length', 
        'min'=>20,
        'tooSmall'=>'You must enter minimum 20 characters',
),

Maximum Length Validation


array('username', 'length', 
        'max'=>45,
        'tooBig'=>'You cannot enter more than 45 characters',
    ),

preg_match(pattern) Validation


//username validation
array('username', 'match' ,
        'pattern'=> '/^[A-Za-z0-9_]+$/u',
        'message'=> 'Username can contain only [a-zA-Z0-9_].'
    ),

Range Validation


array('status', 'in', 
        'range'=>array(1,2,3),
        'allowEmpty'=>false,
        'strict'=>true,// type comparison
    ),

Required Validation


array('username,password,confirmpassword','required'),

Unique Validation


array('username, email','unique',
        'caseSensitive'=>true,
        'allowEmpty'=>true,    
),

URL Validation


array('siteurl', 'url'),

Custom Function Validation


//phone number, mobile number, std code validation
array('phoneno,mobileno,stdcode','my_required'),

//custom function 
public function my_required($attribute_name,$params)
{
    if(empty($this->phoneno) && empty($this->mobileno))
    {
        $this->addError('phoneno',
            'Please enter Telephone number or Mobile number');
    }else if(!empty($this->phoneno) && $this->stdcode=='')
    {
        $this->addError('stdcode','Please enter STD number');
    }
}

Scenario Validation


array('username,password,confirmpassword', 'required', 'on'=>'newuser'),
array('password', 'compare', 
            'compareAttribute'=>'confirmpassword', 
            'on'=>'updatepassword, newuser'),

Filter:trim


array('username, age, firstname, lastname',
            'filter', 'filter'=>'trim'),    

Filter:strtoupper


array('username',
            'filter', 'filter'=>'strtoupper'),    

Filter :Save HTML In Database(htmlpurifier)

CHtmlPurifier is wrapper of HTML Purifier. CHtmlPurifier removes all malicious code. since HTML Purifier is a big package and its performance is not very good

<?php
$purifier = new CHtmlPurifier();
$post->text = $purifier->purify($post->text);
$post->save();
// OR
public function rules()
{
    return array(
        array('myattribute','filter',
            'filter'=>array($object=new CHtmlPurifier(),'purify')),
        );
}
// OR
public function beforeSave()
{
    $purifier = new CHtmlPurifier();
    $this->text = $purifier->purify($this->text);
    return parent::beforeSave()
}
?>

Sample Model


<?php
class Mytable extends CActiveRecord
{
    public static function model($className=__CLASS__){
        return parent::model($className);
    }

    public function rules()
    {
        return array(
            array('status', 'numerical', 'integerOnly'=>true),
            array('username, password, firstname, lastname, contactno', 'length', 'max'=>45),
            array('gender, newsletter', 'length', 'max'=>1),

            /** Username validation in yii model **/
            array('username', 'match' ,'pattern'=>'/^[A-Za-z0-9_]+$/u',
                'message'=> 'Username can contain only alphanumeric characters and hyphens(-).'),

            /** 
            Set scenario for model. Yii Scenario will help you to change dynamic validation using controller.
            $model=Mytable::model()->findByPk($id); //(OR) $model = new Mytable();
            $model->setScenario('updateuser'); // (OR) $model->scenario ='updateuser';
            **/ 
            array('username','unique','on'=>'updateuser'),


            /** EMAIL VALIDATION **/
            //Yii M odel Rules For Email
            array('emailid', 'length', 'max'=>225),
            array('emailid', 'email'),

            /** PASSWORD VALIDATION **/
            //Yii Model Rules For Password Confirm
            array('password', 'compare', 'on'=>"confirmpassword", 
			        'compareAttribute'=>'password'),

            //Yii Model alphanumeric password validation
            array('password','passwordalphanumeric','on'=>'changepassword'), 

            /** DATE VALIDATION **/
            //Yii Model Rules For Date Format
            array('dob', 'type', 'type' =>'date', 
                        'message' => '{attribute}: is not a date!', 
                        'dateFormat' => 'yyyy-MM-dd'),

            /** SIMPLE PHONE NUMBER VALIDATION **/
            //Yii Model Rules For Entering Mobile Or Phone Number
            array('stdcode,phoneno,mobileno', 'numerical', 'integerOnly'=>true),

            //Validation without STD CODE NUMBER
            array('phoneno,mobileno','my_required'),
            //(OR)
            //Validation with STD CODE NUMBER
            array('phoneno,mobileno,stdcode','my_required'),

            /** TRIM DATA BEFORE SEND TO DATABASE **/
            //Yii Model Rules For Trimming Data
            array('username', 'filter', 'filter'=>'trim'),

            /** UNIQUE VALIDATION **/
            //Yii Model Rules For Unique data
            array('username', 'unique'),
            /** Yii Float Number VALIDATION **/
            array('ratio', 'match', 'pattern'=>'/^[0-9]{1,3}(\.[0-9]{0,2})?$/'),

            /** Value In Condition **/
            array('status', 'in', 'range'=>array(1,2,3)),

        );
    }



    // BeforeValidate function in yii rules
    public function beforeValidate() 
    {
        if (!$this->phoneno && !$this->mobileno) 
        {
            $this->addError('mobileno', 'Enter Mobile Number Or Phone Number');
        }
        return parent::beforeValidate();
    }

    // User defined function 
    //Validation without STD CODE NUMBER
    public function my_required($attribute_name,$params)
    {
        if(empty($this->phoneno) && empty($this->mobileno))
        {
            $this->addError($attribute_name,
                    'Please enter Telephone number or Mobile number');
        }
    }

    //Validation with STD CODE NUMBER
    public function my_required($attribute_name,$params)
    {
        if(empty($this->phoneno) && empty($this->mobileno))
        {
            $this->addError('phoneno',
                    'Please enter Telephone number or Mobile number');
        }else if(!empty($this->phoneno) && $this->stdcode=='')
        {
            $this->addError('stdcode','Please enter STD number');
        }
    }

    // Check password with alphanumeric validation
    public function passwordalphanumeric($attribute_name,$params)
    {
        if(!empty($this->password))
        {
            if (preg_match('~^[a-z0-9]*[0-9][a-z0-9]*$~i',$this->password))
            {
                // $subject is alphanumeric and contains at least 1 number
            } else { // failed
                $this->addError($attribute_name,'Please enter password with digits');
            } 
        }
    }
}
?>

  • This website was… how do I say it? Relevant!

    ! Finally I have found something which helped me.
    Appreciate it!

  • sarika ghodke

    this is perfect code and very simple so developers are understanding very easily.

  • thanks a lot.. nice tutorial bro..

  • savoo

    nice and very useful.

  • Ram Pukar

    Nice Website Very Helpfull

  • mohit

    w
    s

  • Omkar

    Great information. Thanks for sharing!