Difference between #21 and #16 of Reference: Model rules validation

unchanged
Title
Reference: Model rules validation
changed
Category
TutorialsHow-tos
changed
Tags
Form validation, model, validation, referencereference,
validation rules, validator
changed
Content
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](http://www.yiiframework.com/doc/guide/1.1/en/form.model#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.

~~~
[php]
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
[Model::rules()][CModel::rules()] function may look
like. The arrays in
In the main arrayarray, each one
setsline 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 validation. a validator

~~~
[php]
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](#choice-of-validators) 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:

1. A method in the model class with the same name as the validator specified.
2. A built-in validator in Yii that extends the
CValidator[CValidator] class.
3. A path/alias to a home made  CValidator class (extending 
[CValidator]) that is not built in.

Here is an example of these 3 kinds:

~~~
[php]
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

TODO: Write shortly about 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.

### Standard parametersFor instance, a [CActiveRecord] read from
the database has the "update" scenario,
while a new record has the "insert" scenario.

~~~
[php]
array(
	'attribute list', 
	'validator name', 
	'on'=>'scenario name', 
	'message'=>'The attribute didn\'t validate!', 
	...validation parameters...
);$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
~~~

+ `attribute list`: specifiesAs shown in the
attributes (separated by commas) to be validated;
+ `validator name`: specifiesexample of the validator to
be used.
+ `on`: this specifiesfirst section, the scenarios when
the validation rule shouldrules can 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
parametersrestricted to be used bya specific
scenario
through the specified validator.`"on" =>
"scenario"` parameter.


## Validation rules reference

+ `boolean` : [CBooleanValidator], validates thatFor each
rule, the attribute value is either trueValue or falseValue.
1. `allowEmpty`, whether the attribute value can be null or empty.
1. `falseValue`, the value representing false status.
1. `strict`, whether the comparison to trueValue and falseValuelist
of its specific arguments is strict.
1. `trueValue`,given with the eventual default value
representing true status.*(in italics)*.

+ `captcha`### `boolean` : [CCaptchaValidator],
validates[CBooleanValidator]
Validates that the attribute value is the same as the verification
code displayed in the CAPTCHA.
1. `allowEmpty`, whether the attribute value can be nulleither
trueValue or empty.
2. `captchaAction`, ID of the action that renders the CAPTCHA image.
3. `caseSensitive`, whether the comparison is case
sensitive.falseValue.

+ `compare` : [CCompareValidator], compares the specified attribute value
with another value and validates if they are equal.
1. `allowEmpty`,1. **allowEmpty**, whether the attribute value
can be null or empty.
2. `compareAttribute`, *(true)*
1. **falseValue**, the name of the attribute to be compared with.
3. `compareValue`, the constant value to be compared with.
4. `operator`, the operator for comparison.
5. `strict`,representing false status. *(0)*
1. **strict**, whether the comparison to trueValue and
falseValue is strict (bothstrict. *(false)*
1. **trueValue**, the value and type must be the
same.representing true status. *(1)*

+ `date`### `captcha` : [CDateValidator],
validates[CCaptchaValidator]
Validates that the attribute value is a valid date, time or datetime.
1. `allowEmpty`, whether the attribute value can be null or empty.
2. `format`, value format. Can be an array or a string. By default it's
'MM/dd/yyyy'. All other formats are describedsame as the verification
code displayed in [CDateTimeParser] API.
3. `timestampAttribute`, name of the attribute that will receive date
parsing result. By default the value is null.
4. NOTE: The date validator was added in Yii **1.1.7** - it's not available
prior to thatCAPTCHA.

   Example of date rule ('allowEmpty' defaults to true);
   ~~~
   [php]
   array('org_datetime', 'date','format'=>'yyyy-M-d H:m:s'),
   ~~~1. **allowEmpty**, whether the attribute value can be null or
empty. *(false)*
2. **caseSensitive**, whether the comparison is case sensitive. *(false)*

+ `default`### `compare` : [CDefaultValueValidator],
sets the attributes with[CCompareValidator]
Compares the specified value. It does not do validation. Its
existence is mainly to allow specifying attribute default values in a
dynamic way.
1. `setOnEmpty`, whether to set the default value only when the
attributewith another value is null or empty string.
2. `value`, the default value to be set to the specified
attributes.and validates if they are equal.

+ `email` : [CEmailValidator], validates that the attribute value is a
valid email address.
1. `allowEmpty`,1. **allowEmpty**, whether the attribute value
can be null or empty. *(false)*
2. `allowName`, whether to allow**compareAttribute**, the
name inof the email address. 
3. `checkMX`, whetherattribute to checkbe
compared with.
3. **compareValue**, the MX record forconstant value to be
compared with.
4. **operator**, the email address.
4. `checkPort`, whether to check port 25operator for the
email address.comparison. *("==")*
5. `fullPattern`,**strict**, whether the regular
expression used to validate email addresses withcomparison is strict
(both value and type must be the name part.
6. `pattern`, the regular expression used to validate the attribute
value.same). *(false)*

+ `exist`### `date` : [CExistValidator],
validates[CDateValidator]
Validates that the attribute value exists inis a
table.
1. `allowEmpty`, whether the attribute value can be nullvalid date,
time or empty.
2. `attributeName`, the ActiveRecord class attribute name that should be used to
look for the attribute value being validated.
3. `className`, the ActiveRecord class name that should be used to look for the
attribute value being validated.
4. `criteria`, additional query criteria.datetime.

+ `file` : [CFileValidator], verifies if an attribute is receiving a valid
uploaded file.
1. `allowEmpty`,1. **allowEmpty**, whether the attribute
requires a file tovalue can be
uploadednull or not.empty. *(true)*
2. `maxFiles`,**format**, the maximum file
countformat pattern that the given
attributedate value should follow.
   This can hold.be either a string or an array
representing multiple formats.
   The formats are described in [CDateTimeParser] API. *('MM/dd/yyyy')*
3. `maxSize`, the maximum number**timestampAttribute**,
name of bytes required for the uploaded file.
4. `minSize`, the minimum number of bytes required for the uploaded file.
5. `tooLarge`, the error message used when the uploaded file is too large.
6. `tooMany`, the error message used if the count of multiple uploads exceeds
limit.
7. `tooSmall`,  	the error message used when the uploaded file is too small.
8. `types`, a list of file name extensions that are allowed to be uploaded.
9. `wrongType`, the error message used when the uploaded file has an extension
nameattribute that is not listed among
extensions.will receive date parsing result. *(null)*

+ `filter` : [CFilterValidator], transforms the data being validated based
on a filter.
1. `filter`, the filter method.*NOTE:* The date validator was added
in Yii **1.1.7** - it's not available prior to that

+ `in` : [CRangeValidator], validates that the attribute value is among the
list (specified via range).
1. `allowEmpty`, whether the attribute value can be null or empty.
2. `range`, list of valid values that the attribute value should be among.
3. `strict`, whether the comparison is strict (both type and value must be the
same).*Example:*

+ `length` : [CStringValidator], validates that the attribute value is of
certain length.
1. `allowEmpty`, whether the attribute value can be null or empty.
2. `encoding` , string encoding.
3. `is`, exact length.
4. `max`, maximum length.
5. `min`, minimum length.
6. `tooLong`, user-defined error message used when the value is too long.
7. `tooShort`, user-defined error message used when the value is too
short.~~~
[php]
array('org_datetime', 'date', 'format'=>'yyyy-M-d H:m:s'),
~~~

+ `numerical`### `default` : [CNumberValidator],
validates that[CDefaultValueValidator]
Sets the attributes with the specified value.
It does not do validation.
Its existence is mainly to allow specifying attribute value
isdefault values in a number.
1. `allowEmpty`, whether the attribute value can be null or empty.
2. `integerOnly`, whether the attribute value can only be an integer.
3. `max`, upper limit of the number.
4. `min`, lower limit of the number.
5. `tooBig`, user-defined error message used when the value is too big.
6. `tooSmall`, user-defined error message used when the value is too
small.dynamic way.

+ `match` : [CRegularExpressionValidator], validates that1.
**setOnEmpty**, whether to set the attributedefault
value matches to the specified regular expression.
1. `allowEmpty`, whetheronly when the attribute value can
beis null or empty.empty string. *(true)*
2. `pattern`,**value**, the regular
expressiondefault value to be matched with.set
to the specified attributes.

+ `required`### `email` : [CRequiredValidator],
validates[CEmailValidator]
Validates that the specified attribute does not have null
or empty value.
1. `requiredValue`, the desired value that the attribute must have.
2. `strict`, whether the comparison to requiredValue is
strict.a valid email address.

+ `safe` : [CSafeValidator], marks1. **allowEmpty**,
whether the associated attributes toattribute value
can be safenull or empty. *(true)*
2. **allowName**, whether to allow name in the email address. *(false)*
3. **checkMX**, whether to check the MX record for massive
assignments.the email address. *(false)*
4. **checkPort**, whether to check port 25 for the email address. *(false)*
5. **fullPattern**, the regular expression used to validate email addresses with
the name part.
   Requires that the property "allowname" is on.
6. **pattern**, the regular expression used to validate the attribute
value.

+### `exist` : [CExistValidator]
Validates that the attribute value exists in a table.

1. **allowEmpty**, whether the attribute value can be null or empty. *(true)*
2. **attributeName**, the ActiveRecord class attribute name that should be used
to look for the attribute value being validated. *(null, meaning same attribute
name)*
3. **className**, the ActiveRecord class name that should be used to look for
the attribute value being validated. *(null, meaning same class name)*
4. **criteria**, additional query criteria. *(array())*

### `file` : [CFileValidator]
Verifies if an attribute is receiving a valid uploaded file.

1. **allowEmpty**, whether the attribute requires a file to be uploaded or not.
*(false)*
2. **maxFiles**, the maximum file count the given attribute can hold. *(1)*
3. **maxSize**, the maximum number of bytes required for the uploaded file.
*(null, meaning no limit)*
4. **minSize**, the minimum number of bytes required for the uploaded file.
*(null, meaning no limit)*
5. **tooLarge**, the error message used when the uploaded file is too large.
6. **tooMany**, the error message used if the count of multiple uploads exceeds
limit.
7. **tooSmall**, the error message used when the uploaded file is too small.
8. **types**, a list of file name extensions that are allowed to be uploaded.
*(null, meaning all extensions)*
9. **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.

1. **filter**, the filter method.

### `in` : [CRangeValidator]
Validates that the attribute value is among the list (specified via range).

1. **allowEmpty**, whether the attribute value can be null or empty. *(true)*
2. **not**, whether to invert the validation logic. Since Yii 1.1.5. *(false)*
3. **range**, list of valid values that the attribute value should be among.
4. **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.

1. **allowEmpty**, whether the attribute value can be null or empty. *(true)*
2. **encoding** , string encoding. *(null, meaning unchecked)*
3. **is**, exact length. *(null, meaning no limit)*
4. **max**, maximum length. *(null, meaning no limit)*
5. **min**, minimum length. *(null, meaning no limit)*
6. **tooLong**, user-defined error message used when the value is too long.
7. **tooShort**, user-defined error message used when the value is too short.

### `numerical` : [CNumberValidator]
Validates that the attribute value is a number.

1. **allowEmpty**, whether the attribute value can be null or empty. *(true)*
2. **integerOnly**, whether the attribute value can only be an integer.
*(false)*
3. **max**, upper limit of the number. *(null, meaning no limit)*
4. **min**, lower limit of the number. *(null, meaning no limit)*
5. **tooBig**, user-defined error message used when the value is too big.
6. **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.

1. **allowEmpty**, whether the attribute value can be null or empty. *(true)*
2. **not**, whether to invert the validation logic. Since Yii 1.1.5. *(false)*
3. **pattern**, the regular expression to be matched with.

### `required` : [CRequiredValidator]
Validates that the specified attribute does not have null or empty value.

1. **requiredValue**, the desired value that the attribute must have. *(null)*
2. **strict**, whether the comparison to "requiredValue" is strict.
*(false)*

### `safe` : [CSafeValidator]
Marks the associated attributes to be safe for massive assignments.

### `type` : [CTypeValidator], verifies[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.
1. `allowEmpty`, whether the attribute value can be null or empty.
2. `dateFormat`, the format pattern that the date value should follow.
3. `datetimeFormat`, the format pattern that the datetime value should follow.
4. `timeFormat`, the format pattern that the time value should follow.
5. `type`, the data type that the attribute should be.

   Example of1. **allowEmpty**, whether the attribute value can
be null or empty. *(true)*
2. **dateFormat**, the format pattern that the date value should follow.
*('MM/dd/yyyy')*
3. **datetimeFormat**, the format pattern that the datetime value should follow.
*('MM/dd/yyyy hh:mm')*
4. **timeFormat**, the format pattern that the time rule;
   ~~~
   [php]
   array('org_starttime, org_finishtime', 'type', 'type'=>'time',
'timeFormat'=>'hh:mm'),
   ~~~value should follow. *('hh:mm')*
5. **type**, the data type that the attribute should be. *('string')*

+ `unique` : [CUniqueValidator], validates that the attribute value is
unique in the corresponding database table.
1. `allowEmpty`, whether the attribute value can be null or empty.
2. `attributeName`, the ActiveRecord class attribute name that should be used to
look for the attribute value being validated.
3. `caseSensitive`, whether the comparison is case sensitive.
4. `className`, the ActiveRecord class name that should be used to look for the
attribute value being validated.
5. `criteria`, additional query criteria.Example of time rule;
~~~
[php]
array('org_starttime, org_finishtime', 'type', 'type'=>'time',
'timeFormat'=>'hh:mm'),
~~~

    By default, CUniqueValidator works with a single attribute that's
presumed to be
    unique across### `unique` : [CUniqueValidator]
Validates that the whole model table, but it can work with
multi-attributeattribute value is unique
    constraints as well. See [CUniqueValidator::c2215] for an
example. in the corresponding database table.

+ `unsafe` : [CUnsafeValidator], marks1. **allowEmpty**,
whether the associated attributes toattribute value
can be unsafe sonull or empty. *(true)*
2. **attributeName**, the ActiveRecord class attribute name that they
cannotshould be massively assigned.used to look
for the attribute value being validated. *(null, meaning same attribute name)*
3. **caseSensitive**, whether the comparison is case sensitive. *(true)*
4. **className**, the ActiveRecord class name that should be used to look for
the attribute value being validated. *(null, meaning same class name)*
5. **criteria**, additional query criteria. *(array())*
6. **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[CUrlValidator]
Validates that the attribute value is a valid
http"http" or
https"https" URL.
1. `allowEmpty`,

1. **allowEmpty**, whether the attribute value can be null or empty.
*(true)*
2. `pattern`,**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)*
3. **pattern**, the regular expression used to validates the attribute
value.
4. **validSchemes**, the allowed URI scheme. *(array('http', 'https'))*

## Selected readings
[The
* [The Definitive Guide to Yii: Working with Forms - Creating
Model](/doc/guide/form.model)<br />
[CModel::validate()]<br />
[CModel::rules()]<br />
[CModel::$scenario]<br />
[CValidator]<br />
[CInlineValidator]Model](/doc/guide/form.model)
* [CModel::validate()]
* [CModel::rules()]
* [CModel::$scenario]
* [CValidator]
* [CInlineValidator]

### Built in validators in Yii
[CBooleanValidator]<br />
[CCaptchaValidator]<br />
[CCompareValidator]<br />
[CDefaultValueValidator]<br />
[CEmailValidator]<br />
[CExistValidator]<br />
[CFileValidator]<br />
[CFilterValidator]<br />
[CNumberValidator]<br />
[CRangeValidator]<br />
[CRegularExpressionValidator]<br />
[CRequiredValidator]<br />
[CSafeValidator]<br />
[CStringValidator]<br />
[CTypeValidator]<br />
[CUniqueValidator]<br />
[CUnsafeValidator]<br />
[CUrlValidator]

Links
-----
- [Chinese version](http://www.itkuaixun.com/bbs/thread-215-1-1.html
"Chinese version")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](http://www.yiiframework.com/doc/api/1.1/CValidator#nav).

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