Yii Framework 1.0 Tutorial

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()'), 

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()'),		

Update First Time

array('updated_on', 'default',
		'value'=>new CDbExpression('NOW()'),		

Compare Validation

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

Date/Time Validation

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

Email Validation

array('emailid', 'email'),

File Validation

array('userimage', 'file', 
		'types'=>'jpg, gif, png', 
		'message' => 'Upload Valid Image!',  // Error message
		'wrongType'=>'File type is Invalid',
		'minSize'=>1024,// 1MB
		'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', 
    'tooSmall'=>'You must enter minimum 20 characters',


Maximum Length Validation

array('username', 'length', 
    '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', 
    'strict'=>true,// type comparison

Required Validation


Unique Validation

array('username, email','unique',

URL Validation

array('siteurl', 'url'),

Custom Function Validation

//phone number, mobile number, std code validation

//custom function 
public function my_required($attribute_name,$params){
     if(empty($this->phoneno) && empty($this->mobileno)){
                 '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'),


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


            '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

$purifier = new CHtmlPurifier();
$post->text = $purifier->purify($post->text);
// 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

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

    public function rules() {
        return array(
            array('status', 'numerical', 'integerOnly' = & gt; true),
            array('username, password, firstname, lastname, contactno', 'length', 'max' = & gt; 45),
            array('gender, newsletter', 'length', 'max' = & gt; 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' = & gt;

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

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

            //Yii Model alphanumeric password validation
            array('password', 'passwordalphanumeric', 'on' = & gt;

            /** DATE VALIDATION **/
            //Yii Model Rules For Date Format
            array('dob', 'type', 'type' = & gt;
                'message' = & gt;
                '{attribute}: is not a date!', 'dateFormat' = & gt;

            //Yii Model Rules For Entering Mobile Or Phone Number
            array('stdcode,phoneno,mobileno', 'numerical', 'integerOnly' = & gt; true),

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

            //Yii Model Rules For Trimming Data
            array('username', 'filter', 'filter' = & gt;

            /** 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 - & gt; phoneno) & amp; & amp; empty($this - & gt; mobileno)) {
            $this - & gt;
                'Please enter Telephone number or Mobile number');

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

    // Check password with alphanumeric validation
    public function passwordalphanumeric($attribute_name, $params) {
        if (!empty($this - & gt; password)) {
            if (preg_match('~^[a-z0-9]*[0-9][a-z0-9]*$~i', $this - & gt; password)) {
                // $subject is alphanumeric and contains at least 1 number
            } else { // failed
                $this - & gt;
                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