In this tutorial i explain the Model rules and validation in Yii framework which will 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.
Default Validation
1 2 3 | array('created_on', 'default', 'value'=>new CDbExpression('NOW()'), 'on'=>'insert'), |
Compare Validation
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | //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
1 2 3 4 5 6 7 8 9 10 11 12 | //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
1 | array('emailid', 'email'), |
Unique Validation
1 2 3 4 | array('username, email','unique', 'caseSensitive'=>true, 'allowEmpty'=>true, ), |
Custom Function Validation
1 2 3 4 5 6 7 8 9 10 11 12 | //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'); } } |
URL Validation
1 | array('siteurl', 'url'), |
Range Validation
1 2 3 4 5 | array('status', 'in', 'range'=>array(1,2,3), 'allowEmpty'=>false, 'strict'=>true,// type comparison ), |
preg_match(pattern) Validation
1 2 3 4 5 | //username validation array('username', 'match' , 'pattern'=> '/^[A-Za-z0-9_]+$/u', 'message'=> 'Username can contain only [a-zA-Z0-9_].' ), |
File Validation
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | 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 ), |
Required Validation
1 | array('username,password,confirmpassword','required'), |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 | <?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'); } } } } ?> |
If you like FreeWebMentor and you would like to contribute, you can write an article and mail your article to [email protected] Your article will appear on the FreeWebMentor main page and help other developers.
Article Tags: Php Framework, Yii