Reference: Model rules validation

You are viewing revision #15 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 (#14)next (#16) »

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

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:

  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 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

  • boolean : [CBooleanValidator], validates that the attribute value is either trueValue or falseValue.

    1. allowEmpty, whether the attribute value can be null or empty.
    2. falseValue, the value representing false status.
    3. strict, whether the comparison to trueValue and falseValue is strict.
    4. trueValue, the value representing true status.
  • captcha : [CCaptchaValidator], validates that the attribute value is the same as the verification code displayed in the CAPTCHA.

    1. allowEmpty, whether the attribute value can be null or empty.
    2. captchaAction, ID of the action that renders the CAPTCHA image.
    3. caseSensitive, whether the comparison is case sensitive.
  • compare : [CCompareValidator], compares the specified attribute value with another value and validates if they are equal.

    1. allowEmpty, whether the attribute value can be null or empty.
    2. compareAttribute, 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, whether the comparison is strict (both value and type must be the same.
  • date : [CDateValidator], 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 described 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 that

    Example of date rule ('allowEmpty' defaults to true); ~~~ [php] 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.

    1. setOnEmpty, whether to set the default value only when the attribute value is null or empty string.
    2. value, the default value to be set to the specified attributes.
  • email : [CEmailValidator], validates that the attribute value is a valid email address.

    1. allowEmpty, whether the attribute value can be null or empty.
    2. allowName, whether to allow name in the email address.
    3. checkMX, whether to check the MX record for the email address.
    4. checkPort, whether to check port 25 for the email address.
    5. fullPattern, the regular expression used to validate email addresses with the name part.
    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.
    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.
  • 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.
    2. maxFiles, the maximum file count the given attribute can hold.
    3. maxSize, the maximum number 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 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.
    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).
  • 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 short.
    7. tooShort, user-defined error message used when the value is too long.
  • numerical : [CNumberValidator], validates that the attribute value is 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.
  • match : [CRegularExpressionValidator], validates that the attribute value matches to the specified regular expression.

    1. allowEmpty, whether the attribute value can be null or empty.
    2. 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.
    2. 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.

    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 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.

    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.

    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.

    1. allowEmpty, whether the attribute value can be null or empty.
    2. 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]

Links

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

Revisions

View all history

Related Articles