Reference: Model rules validation

You are viewing revision #2 of this wiki article.
This version may not be up to date with the latest version.
You may want to view the differences to the latest version or see the changes made in this revision.

« previous (#1)next (#3) »

  1. How validation works
  2. Validation rules reference
  3. Selected readings

This is a reference to be used for Model rule validation and is compiled from the Yii documentation and code. The purpose is to have all the information gathered in one place instead of scattered. This reference is not an intro.

Applys to Yii: 1.0.10

How validation works

The CModel class uses a method named rules to return an array with the rules for validation.

public function rules()
{
    return array(
        array('username, password', 'required'),
        array('password_repeat', 'required', 'on'=>'register'),
        array('password', 'compare', 'on'=>'register'),
    );
}

The code above is an example of what the rules() function may look like. The arrays in the main array each one sets a rule of validation.

Choise of validators

Yii will look for validators in the specifik order:

  1. A method in the model class with the same name as the validator specified.
  2. A builtin validator in Yii that extends the CValidator class.
  3. A path/alias to a home made CValidator class that is not built in.
Scenarios

TODO: Write shortly about scenarios.

Standard parameters
array(
	'attribute list', 
	'validator name', 
	'on'=>'scenario name', 
	'message'=>'The attribute didn\'t validate!', 
	...validation parameters...
);
  • attribute list: specifies the attributes (separated by commas) to be validated;
  • validator name: specifies the validator to be used.
  • on: this specifies the scenarios when the validation rule should be performed. Separate different scenarios with commas. If this option is not set, the rule will be applied in any scenario.
  • message: Error message if validation fails.
  • ...validation parameters...: any number of extra parameters to be used by the specified validator.

Validation rules reference

Selected readings

The Definitive Guide to Yii: Working with Forms - Creating Model
CModel::validate()
CModel::rules()
CModel::$scenario
CValidator
CInlineValidator

Built in validators in Yii

CBooleanValidator
CCaptchaValidator
CCompareValidator
CDefaultValueValidator
CEmailValidator
CExistValidator
CFileValidator
CFilterValidator
CNumberValidator
CRangeValidator
CRegularExpressionValidator
CRequiredValidator
CSafeValidator
CStringValidator
CTypeValidator
CUniqueValidator
CUnsafeValidator
CUrlValidator

99 0
114 followers
Viewed: 885 170 times
Version: Unknown (update)
Category: Tutorials
Written by: krillzip
Last updated by: Rodrigo
Created on: Nov 29, 2009
Last updated: 10 years ago
Update Article

Revisions

View all history

Related Articles