You are viewing revision #21 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.
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.
How validation works ¶
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.
Parameters of a validator ¶
array(
// mandatory arguments
'attribute list',
'validator name',
// optional parameters
'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. See the next section for details.
- 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. See the section [Scenarios][#Scenarios] for details.
- message: replaces the default error message if validation fails.
- ...validation parameters...: any number of extra parameters to be used by the specified validator.
Choice of validators ¶
Yii will look for validators in the specific order:
- A method in the model class with the same name as the validator specified.
- A built-in validator in Yii that extends the [CValidator] class.
- A path/alias to a home made class (extending [CValidator]) that is not built in.
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() {
Scenarios ¶
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.
Validation rules reference ¶
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.
- allowEmpty, whether the attribute value can be null or empty. (true)
- falseValue, the value representing false status. (0)
- strict, whether the comparison to trueValue and falseValue is strict. (false)
- trueValue, the value representing true status. (1)
captcha
: [CCaptchaValidator] ¶
Validates that the attribute value is the same as the verification code displayed in the CAPTCHA.
- allowEmpty, whether the attribute value can be null or empty. (false)
- caseSensitive, whether the comparison is case sensitive. (false)
compare
: [CCompareValidator] ¶
Compares the specified attribute value with another value and validates if they are equal.
- allowEmpty, whether the attribute value can be null or empty. (false)
- compareAttribute, the name of the attribute to be compared with.
- compareValue, the constant value to be compared with.
- operator, the operator for comparison. ("==")
- strict, whether the comparison is strict (both value and type must be the same). (false)
date
: [CDateValidator] ¶
Validates that the attribute value is a valid date, time or datetime.
- allowEmpty, whether the attribute value can be null or empty. (true)
- format, the format pattern that the date value should follow. This can be either a string or an array representing multiple formats. The formats are described in [CDateTimeParser] API. ('MM/dd/yyyy')
- timestampAttribute, name of the attribute that will receive date parsing result. (null)
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.
- setOnEmpty, whether to set the default value only when the attribute value is null or empty string. (true)
- value, the default value to be set to the specified attributes.
email
: [CEmailValidator] ¶
Validates that the attribute value is a valid email address.
- allowEmpty, whether the attribute value can be null or empty. (true)
- allowName, whether to allow name in the email address. (false)
- checkMX, whether to check the MX record for the email address. (false)
- checkPort, whether to check port 25 for the email address. (false)
- fullPattern, the regular expression used to validate email addresses with the name part. Requires that the property "allowname" is on.
- pattern, the regular expression used to validate the attribute value.
exist
: [CExistValidator] ¶
Validates that the attribute value exists in a table.
- allowEmpty, whether the attribute value can be null or empty. (true)
- attributeName, the ActiveRecord class attribute name that should be used to look for the attribute value being validated. (null, meaning same attribute name)
- className, the ActiveRecord class name that should be used to look for the attribute value being validated. (null, meaning same class name)
- criteria, additional query criteria. (array())
file
: [CFileValidator] ¶
Verifies if an attribute is receiving a valid uploaded file.
- allowEmpty, whether the attribute requires a file to be uploaded or not. (false)
- maxFiles, the maximum file count the given attribute can hold. (1)
- maxSize, the maximum number of bytes required for the uploaded file. (null, meaning no limit)
- minSize, the minimum number of bytes required for the uploaded file. (null, meaning no limit)
- tooLarge, the error message used when the uploaded file is too large.
- tooMany, the error message used if the count of multiple uploads exceeds limit.
- tooSmall, the error message used when the uploaded file is too small.
- types, a list of file name extensions that are allowed to be uploaded. (null, meaning all extensions)
- wrongType, the error message used when the uploaded file has an extension name that is not listed among extensions.
filter
: [CFilterValidator] ¶
Transforms the data being validated based on a filter.
- filter, the filter method.
in
: [CRangeValidator] ¶
Validates that the attribute value is among the list (specified via range).
- allowEmpty, whether the attribute value can be null or empty. (true)
- not, whether to invert the validation logic. Since Yii 1.1.5. (false)
- range, list of valid values that the attribute value should be among.
- strict, whether the comparison is strict (both type and value must be the same). (false)
length
: [CStringValidator] ¶
Validates that the attribute value is of certain length.
- allowEmpty, whether the attribute value can be null or empty. (true)
- encoding , string encoding. (null, meaning unchecked)
- is, exact length. (null, meaning no limit)
- max, maximum length. (null, meaning no limit)
- min, minimum length. (null, meaning no limit)
- tooLong, user-defined error message used when the value is too long.
- tooShort, user-defined error message used when the value is too short.
numerical
: [CNumberValidator] ¶
Validates that the attribute value is a number.
- allowEmpty, whether the attribute value can be null or empty. (true)
- integerOnly, whether the attribute value can only be an integer. (false)
- max, upper limit of the number. (null, meaning no limit)
- min, lower limit of the number. (null, meaning no limit)
- tooBig, user-defined error message used when the value is too big.
- tooSmall, user-defined error message used when the value is too small.
match
: [CRegularExpressionValidator] ¶
Validates that the attribute value matches to the specified regular expression.
- allowEmpty, whether the attribute value can be null or empty. (true)
- not, whether to invert the validation logic. Since Yii 1.1.5. (false)
- pattern, the regular expression to be matched with.
required
: [CRequiredValidator] ¶
Validates that the specified attribute does not have null or empty value.
- requiredValue, the desired value that the attribute must have. (null)
- strict, whether the comparison to "requiredValue" is strict. (false)
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.
- allowEmpty, whether the attribute value can be null or empty. (true)
- dateFormat, the format pattern that the date value should follow. ('MM/dd/yyyy')
- datetimeFormat, the format pattern that the datetime value should follow. ('MM/dd/yyyy hh:mm')
- timeFormat, the format pattern that the time value should follow. ('hh:mm')
- type, the data type that the attribute should be. ('string')
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.
- allowEmpty, whether the attribute value can be null or empty. (true)
- attributeName, the ActiveRecord class attribute name that should be used to look for the attribute value being validated. (null, meaning same attribute name)
- caseSensitive, whether the comparison is case sensitive. (true)
- className, the ActiveRecord class name that should be used to look for the attribute value being validated. (null, meaning same class name)
- criteria, additional query criteria. (array())
- skipOnError, whether this validation rule should be skipped if when there is already a validation error for the current attribute. (true)
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.
- allowEmpty, whether the attribute value can be null or empty. (true)
- defaultScheme, the default URI scheme. It will be prepended to the input, if the input doesn't contain one. Since Yii 1.1.7. (null, meaning the url must contain a scheme part)
- pattern, the regular expression used to validates the attribute value.
- validSchemes, the allowed URI scheme. (array('http', 'https'))
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 ¶
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.
- [CBooleanValidator]
- [CCaptchaValidator]
- [CCompareValidator]
- [CDefaultValueValidator]
- [CEmailValidator]
- [CExistValidator]
- [CFileValidator]
- [CFilterValidator]
- [CNumberValidator]
- [CRangeValidator]
- [CRegularExpressionValidator]
- [CRequiredValidator]
- [CSafeValidator]
- [CStringValidator]
- [CTypeValidator]
- [CUniqueValidator]
- [CUnsafeValidator]
- [CUrlValidator]
compare operator default behavior
by default,
array('password', 'compare', 'on'=>'register')
compare with password_repeat. If you do not explicitly state what to compare. It will compare with comparedfield_repeat
CFilterValidator?
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
compare operator against avalue
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;
array('field_prop', 'compare', 'compareValue'=>'Y', 'message'=>'Your only choice is YES'),
Assuming that you have yes/no drop down and Y/N as values
File rule safe attribute
Hallo,
I found out that I have to set the safe rule attribute to true for the file rule.
array('myFile', 'file','safe'=>true, 'allowEmpty' => false, 'types'=>'pdf,docx', 'on' => 'myScenario'),
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 :)
Rule compare myDate with now()
How to compare myDate and now() with operator is '>=' ?
Rule compare myDate with now()
Hello nakovn, it is a little late but perhaps will be usefull for anyone
array('mydate','compare','compareValue'=>date('Y-m-d'),'operator'=>'>=')
custom date validation
HI i Have date in day(dob_days), month(dob_months) and year(dob_years) dropdowns and I want to validate date using yii. How can i do so? I am new to yii can anyone guide me? Also if is require custom rule, how can i take these 3 parameters into custom validation in model?
If you have any questions, please ask in the forum instead.
Signup or Login in order to comment.