system system.base system.caching system.caching.dependencies system.collections system.console system.db system.db.ar system.db.schema system.db.schema.cubrid system.db.schema.mssql system.db.schema.mysql system.db.schema.oci system.db.schema.pgsql system.db.schema.sqlite system.gii system.i18n system.i18n.gettext system.logging system.test system.utils system.validators system.web system.web.actions system.web.auth system.web.filters system.web.form system.web.helpers system.web.renderers system.web.services system.web.widgets system.web.widgets.captcha system.web.widgets.pagers zii.behaviors zii.widgets zii.widgets.grid zii.widgets.jui

CValidator

system.validators
继承 abstract class CValidator » CComponent
子类 CBooleanValidator, CCaptchaValidator, CCompareValidator, CDateValidator, CDefaultValueValidator, CEmailValidator, CExistValidator, CFileValidator, CFilterValidator, CInlineValidator, CNumberValidator, CRangeValidator, CRegularExpressionValidator, CRequiredValidator, CSafeValidator, CStringValidator, CTypeValidator, CUniqueValidator, CUnsafeValidator, CUrlValidator
可用自 1.0
源码 framework/validators/CValidator.php
CValidator is the base class for all validators.

Child classes must implement the validateAttribute method.

When using createValidator to create a validator, the following aliases are recognized as the corresponding built-in validator classes:

公共属性

隐藏继承的属性

属性类型描述被定义在
attributes array list of attributes to be validated. CValidator
builtInValidators array list of built-in validators (name=>class) CValidator
enableClientValidation boolean whether to perform client-side validation. CValidator
except array list of scenarios that the validator should not be applied to. CValidator
message string the user-defined error message. CValidator
on array list of scenarios that the validator should be applied. CValidator
safe boolean whether attributes listed with this validator should be considered safe for massive assignment. CValidator
skipOnError boolean whether this validation rule should be skipped when there is already a validation error for the current attribute. CValidator

公共方法

隐藏继承的方法

方法描述被定义在
__call() Calls the named method which is not a class method. CComponent
__get() Returns a property value, an event handler list or a behavior based on its name. CComponent
__isset() Checks if a property value is null. CComponent
__set() Sets value of a component property. CComponent
__unset() Sets a component property to be null. CComponent
applyTo() Returns a value indicating whether the validator applies to the specified scenario. CValidator
asa() Returns the named behavior object. CComponent
attachBehavior() Attaches a behavior to this component. CComponent
attachBehaviors() Attaches a list of behaviors to the component. CComponent
attachEventHandler() Attaches an event handler to an event. CComponent
canGetProperty() Determines whether a property can be read. CComponent
canSetProperty() Determines whether a property can be set. CComponent
clientValidateAttribute() Returns the JavaScript needed for performing client-side validation. CValidator
createValidator() Creates a validator object. CValidator
detachBehavior() Detaches a behavior from the component. CComponent
detachBehaviors() Detaches all behaviors from the component. CComponent
detachEventHandler() Detaches an existing event handler. CComponent
disableBehavior() Disables an attached behavior. CComponent
disableBehaviors() Disables all behaviors attached to this component. CComponent
enableBehavior() Enables an attached behavior. CComponent
enableBehaviors() Enables all behaviors attached to this component. CComponent
evaluateExpression() Evaluates a PHP expression or callback under the context of this component. CComponent
getEventHandlers() Returns the list of attached event handlers for an event. CComponent
hasEvent() Determines whether an event is defined. CComponent
hasEventHandler() Checks whether the named event has attached handlers. CComponent
hasProperty() Determines whether a property is defined. CComponent
raiseEvent() Raises an event. CComponent
validate() Validates the specified object. CValidator

受保护的方法

隐藏继承的方法

方法描述被定义在
addError() Adds an error about the specified attribute to the active record. CValidator
isEmpty() Checks if the given value is empty. CValidator
validateAttribute() Validates a single attribute. CValidator

属性详情

attributes 属性
public array $attributes;

list of attributes to be validated.

builtInValidators 属性
public static array $builtInValidators;

list of built-in validators (name=>class)

enableClientValidation 属性 (自版本 v1.1.7 可用)
public boolean $enableClientValidation;

whether to perform client-side validation. Defaults to true. Please refer to CActiveForm::enableClientValidation for more details about client-side validation.

except 属性 (自版本 v1.1.11 可用)
public array $except;

list of scenarios that the validator should not be applied to. Each array value refers to a scenario name with the same name as its array key.

message 属性
public string $message;

the user-defined error message. Different validators may define various placeholders in the message that are to be replaced with actual values. All validators recognize "{attribute}" placeholder, which will be replaced with the label of the attribute.

on 属性
public array $on;

list of scenarios that the validator should be applied. Each array value refers to a scenario name with the same name as its array key.

safe 属性 (自版本 v1.1.4 可用)
public boolean $safe;

whether attributes listed with this validator should be considered safe for massive assignment. Defaults to true.

skipOnError 属性 (自版本 v1.1.1 可用)
public boolean $skipOnError;

whether this validation rule should be skipped when there is already a validation error for the current attribute. Defaults to false.

方法详情

addError() 方法
protected void addError(CModel $object, string $attribute, string $message, array $params=array ( ))
$object CModel the data object being validated
$attribute string the attribute being validated
$message string the error message
$params array values for the placeholders in the error message
源码: framework/validators/CValidator.php#248 (显示)
protected function addError($object,$attribute,$message,$params=array())
{
    
$params['{attribute}']=$object->getAttributeLabel($attribute);
    
$object->addError($attribute,strtr($message,$params));
}

Adds an error about the specified attribute to the active record. This is a helper method that performs message selection and internationalization.

applyTo() 方法
public boolean applyTo(string $scenario)
$scenario string scenario name
{return} boolean whether the validator applies to the specified scenario.
源码: framework/validators/CValidator.php#233 (显示)
public function applyTo($scenario)
{
    if(isset(
$this->except[$scenario]))
        return 
false;
    return empty(
$this->on) || isset($this->on[$scenario]);
}

Returns a value indicating whether the validator applies to the specified scenario. A validator applies to a scenario as long as any of the following conditions is met:

  • the validator's "on" property is empty
  • the validator's "on" property contains the specified scenario

clientValidateAttribute() 方法 (自版本 v1.1.7 可用)
public string clientValidateAttribute(CModel $object, string $attribute)
$object CModel the data object being validated
$attribute string the name of the attribute to be validated.
{return} string the client-side validation script. Null if the validator does not support client-side validation.
源码: framework/validators/CValidator.php#219 (显示)
public function clientValidateAttribute($object,$attribute)
{
}

Returns the JavaScript needed for performing client-side validation. Do not override this method if the validator does not support client-side validation. Two predefined JavaScript variables can be used:

  • value: the value to be validated
  • messages: an array used to hold the validation error messages for the value

createValidator() 方法
public static CValidator createValidator(string $name, CModel $object, mixed $attributes, array $params=array ( ))
$name string the name or class of the validator
$object CModel the data object being validated that may contain the inline validation method
$attributes mixed list of attributes to be validated. This can be either an array of the attribute names or a string of comma-separated attribute names.
$params array initial values to be applied to the validator properties
{return} CValidator the validator
源码: framework/validators/CValidator.php#129 (显示)
public static function createValidator($name,$object,$attributes,$params=array())
{
    if(
is_string($attributes))
        
$attributes=preg_split('/\s*,\s*/',trim($attributes" \t\n\r\0\x0B,"),-1,PREG_SPLIT_NO_EMPTY);

    if(isset(
$params['on']))
    {
        if(
is_array($params['on']))
            
$on=$params['on'];
        else
            
$on=preg_split('/[\s,]+/',$params['on'],-1,PREG_SPLIT_NO_EMPTY);
    }
    else
        
$on=array();

    if(isset(
$params['except']))
    {
        if(
is_array($params['except']))
            
$except=$params['except'];
        else
            
$except=preg_split('/[\s,]+/',$params['except'],-1,PREG_SPLIT_NO_EMPTY);
    }
    else
        
$except=array();

    if(
method_exists($object,$name))
    {
        
$validator=new CInlineValidator;
        
$validator->attributes=$attributes;
        
$validator->method=$name;
        if(isset(
$params['clientValidate']))
        {
            
$validator->clientValidate=$params['clientValidate'];
            unset(
$params['clientValidate']);
        }
        
$validator->params=$params;
        if(isset(
$params['skipOnError']))
            
$validator->skipOnError=$params['skipOnError'];
    }
    else
    {
        
$params['attributes']=$attributes;
        if(isset(
self::$builtInValidators[$name]))
            
$className=Yii::import(self::$builtInValidators[$name],true);
        else
            
$className=Yii::import($name,true);
        
$validator=new $className;
        foreach(
$params as $name=>$value)
            
$validator->$name=$value;
    }

    
$validator->on=empty($on) ? array() : array_combine($on,$on);
    
$validator->except=empty($except) ? array() : array_combine($except,$except);

    return 
$validator;
}

Creates a validator object.

isEmpty() 方法
protected boolean isEmpty(mixed $value, boolean $trim=false)
$value mixed the value to be checked
$trim boolean whether to perform trimming before checking if the string is empty. Defaults to false.
{return} boolean whether the value is empty
源码: framework/validators/CValidator.php#262 (显示)
protected function isEmpty($value,$trim=false)
{
    return 
$value===null || $value===array() || $value==='' || $trim && is_scalar($value) && trim($value)==='';
}

Checks if the given value is empty. A value is considered empty if it is null, an empty array, or the trimmed result is an empty string. Note that this method is different from PHP empty(). It will return false when the value is 0.

validate() 方法
public void validate(CModel $object, array $attributes=NULL)
$object CModel the data object being validated
$attributes array the list of attributes to be validated. Defaults to null, meaning every attribute listed in attributes will be validated.
源码: framework/validators/CValidator.php#192 (显示)
public function validate($object,$attributes=null)
{
    if(
is_array($attributes))
        
$attributes=array_intersect($this->attributes,$attributes);
    else
        
$attributes=$this->attributes;
    foreach(
$attributes as $attribute)
    {
        if(!
$this->skipOnError || !$object->hasErrors($attribute))
            
$this->validateAttribute($object,$attribute);
    }
}

Validates the specified object.

validateAttribute() 方法
abstract protected void validateAttribute(CModel $object, string $attribute)
$object CModel the data object being validated
$attribute string the name of the attribute to be validated.
源码: framework/validators/CValidator.php#117 (显示)
abstract protected function validateAttribute($object,$attribute);

Validates a single attribute. This method should be overridden by child classes.