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. See The Definitive Guide to Yii, Declaring Validation Rules for a tutorial.
The CModel class uses a method named CModel::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', 'compareAttribute'=>'password_repeat', 'on'=>'register'), ); }
The code above is an example of what the CModel::rules() function may look like. In the main array, each line is an array that declare a new validation rule (described in next section).
These rules are applied by the CModel::validate() method which returns a boolean value. By default, the method CActiveRecord::save() automatically calls this validation, and requires it to succeed before it tries to save the record.
array( // mandatory arguments 'attribute list', 'validator name', // optional parameters 'on'=>'scenario name', 'message'=>'The attribute didn\'t validate!', ...validation parameters... );
Yii will look for validators in the specific order:
Here is an example of these 3 kinds:
public function rules() { return array( array('password', 'validateLogin'), // Custom validation method in this object array('username, password', 'required'), // built-in alias for CRequiredValidator array('username', 'ext.MyValidators.MyLoginValidator'), // Custom validation class ); } public validateLogin() {
Each model object has a scenario property. Some scenarios are built-in and will be assigned automatically by Yii, but you can define your own.
For instance, a CActiveRecord read from the database has the "update" scenario, while a new record has the "insert" scenario.
$modelA = User::model()->findByPk(1); // $model->scenario = 'update' $modelB = new User(); // $model->scenario = 'insert' $modelB->scenario = 'light'; // custom scenario if ($modelB->validate()) { // will only apply rules of the "light" scenario
As shown in the example of the first section, the rules can be restricted to a specific scenario
through the "on" => "scenario" parameter.
For each rule, the list of its specific arguments is given with the eventual default value (in italics).
boolean : CBooleanValidator ¶Validates that the attribute value is either trueValue or falseValue.
captcha : CCaptchaValidator ¶Validates that the attribute value is the same as the verification code displayed in the CAPTCHA.
compare : CCompareValidator ¶Compares the specified attribute value with another value and validates if they are equal.
date : CDateValidator ¶Validates that the attribute value is a valid date, time or datetime.
NOTE: The date validator was added in Yii 1.1.7 - it's not available prior to that
Example:
array('org_datetime', 'date', 'format'=>'yyyy-M-d H:m:s'),
default : CDefaultValueValidator ¶Sets the attributes with the specified value. It does not do validation. Its existence is mainly to allow specifying attribute default values in a dynamic way.
email : CEmailValidator ¶Validates that the attribute value is a valid email address.
exist : CExistValidator ¶Validates that the attribute value exists in a table.
file : CFileValidator ¶Verifies if an attribute is receiving a valid uploaded file.
filter : CFilterValidator ¶Transforms the data being validated based on a filter.
Examples:
array('mycode','filter','filter'=>'strtoupper'),
array('eanupc','filter','filter'=>array($this,'keepProductCode')), array('eanupc','filter','filter'=>array(self,'formatProductCode')), ... public function keepProductCode($code){ // returns a new value (uses $this) ... } static public function formatProductCode($code){ // returns a new value (cannot use $this) ... }
NOTE: The filter validator maybe use with other validators for the same attribute. In this case one must pay attention to the order of the validators list as the filter validator will change the attribute value.
in : CRangeValidator ¶Validates that the attribute value is among the list (specified via range).
Example:
array('language','in','range'=>array('en','fr','zn'),'allowEmpty'=>false),
length : CStringValidator ¶Validates that the attribute value is of certain length.
numerical : CNumberValidator ¶Validates that the attribute value is a number.
Example:
array('quantity','numerical', 'integerOnly'=>true, 'min'=>1, 'max'=>250, 'tooSmall'=>'You must order at least 1 piece', 'tooBig'=>'You cannot order more than 250 pieces at once'),
match : CRegularExpressionValidator ¶Validates that the attribute value matches to the specified regular expression.
required : CRequiredValidator ¶Validates that the specified attribute does not have null or empty value.
safe : CSafeValidator ¶Marks the associated attributes to be safe for massive assignments.
type : CTypeValidator ¶Verifies if the attribute is of the type specified by type. (integer, float, string, date, time, datetime). Since 1.1.7 you should use CDateValidator to validate dates.
Example of time rule;
array('org_starttime, org_finishtime', 'type', 'type'=>'time', 'timeFormat'=>'hh:mm'),
unique : CUniqueValidator ¶Validates that the attribute value is unique in the corresponding database table.
By default, CUniqueValidator works with a single attribute that's presumed to be unique across the whole model table, but it can work with multi-attribute unique constraints as well. See CUniqueValidator::c2215 for an example.
unsafe : CUnsafeValidator ¶Marks the associated attributes to be unsafe so that they cannot be massively assigned.
url : CUrlValidator ¶Validates that the attribute value is a valid "http" or "https" URL.
The validators are all the classes that inherit from CValidator, so the API documentation contains an always up-to-date list in the subclasses description of CValidator.
Total 4 comments
Hallo,
I found out that I have to set the safe rule attribute to true for the file rule.
Why is it default set to false? Is there some explanation somewhere ?
Here is where it is said that its default is FALSE: CFileValidator#safe-detail
thank you :)
Suppose you have a situation where you need to compare against a certain value. The most obvious case is yes/no situation.
You could use compare operator like this;
Assuming that you have yes/no drop down and Y/N as values
The example at the bottom is great but what we really need is a sample of each validator. Currently I am searching how exactly to use CFilterValidator
by default,
compare with password_repeat. If you do not explicitly state what to compare. It will compare with comparedfield_repeat
Leave a comment
Please login to leave your comment.