You are viewing revision #12 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.
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', 'on'=>'register'),
);
}
The code above is an example of what the [Model::rules()] function may look like. The arrays in the main array each one sets a rule of validation.
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 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 ¶
boolean
: [CBooleanValidator], validates that the attribute value is either trueValue or falseValue.allowEmpty
, whether the attribute value can be null or empty.falseValue
, the value representing false status.strict
, whether the comparison to trueValue and falseValue is strict.trueValue
, the value representing true status.
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.captchaAction
, ID of the action that renders the CAPTCHA image.caseSensitive
, whether the comparison is case sensitive.
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.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.
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.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.allowName
, whether to allow name in the email address.checkMX
, whether to check the MX record for the email address.checkPort
, whether to check port 25 for the email address.fullPattern
, the regular expression used to validate email addresses with the name part.pattern
, the regular expression used to validate the attribute value.
date
: [CDateValidator], validates that the attribute value is a valid date, time or datetime.allowEmpty
, whether the attribute value can be null or empty.format
, value format. Can be an array or a string. By default it's 'MM/dd/yyyy'. All other formats are described in [CDateTimeParser] API.timestampAttribute
, name of the attribute that will receive date parsing result. By default the value is null.
exist
: [CExistValidator], validates that the attribute value exists in a table.allowEmpty
, whether the attribute value can be null or empty.attributeName
, the ActiveRecord class attribute name that should be used to look for the attribute value being validated.className
, the ActiveRecord class name that should be used to look for the attribute value being validated.criteria
, additional query criteria.
file
: [CFileValidator], verifies if an attribute is receiving a valid uploaded file.allowEmpty
, whether the attribute requires a file to be uploaded or not.maxFiles
, the maximum file count the given attribute can hold.maxSize
, the maximum number of bytes required for the uploaded file.minSize
, the minimum number of bytes required for the uploaded file.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.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.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).
length
: [CStringValidator], validates that the attribute value is of certain length.allowEmpty
, whether the attribute value can be null or empty.encoding
, string encoding.is
, exact length.max
, maximum length.min
, minimum length.tooLong
, user-defined error message used when the value is too short.tooShort
, user-defined error message used when the value is too long.
numerical
: [CNumberValidator], validates that the attribute value is a number.allowEmpty
, whether the attribute value can be null or empty.integerOnly
, whether the attribute value can only be an integer.max
, upper limit of the number.min
, lower limit of the number.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.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.strict
, whether the comparison to requiredValue is strict.
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.dateFormat
, the format pattern that the date value should follow.datetimeFormat
, the format pattern that the datetime value should follow.timeFormat
, the format pattern that the time value should follow.type
, the data type that the attribute should be.
Example of time rule; ~~~ [php] 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.attributeName
, the ActiveRecord class attribute name that should be used to look for the attribute value being validated.caseSensitive
, whether the comparison is case sensitive.className
, the ActiveRecord class name that should be used to look for the attribute value being validated.criteria
, additional query criteria.
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.pattern
, the regular expression used to validates the attribute value.
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]
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.