Browse Source

w

tags/2.0.0-beta
Qiang Xue 14 years ago
parent
commit
af593aad5e
  1. 11
      classmap.txt
  2. 26
      framework/validators/BooleanValidator.php
  3. 57
      framework/validators/CaptchaValidator.php
  4. 90
      framework/validators/CompareValidator.php
  5. 30
      framework/validators/DefaultValueValidator.php
  6. 1
      framework/validators/EmailValidator.php
  7. 42
      framework/validators/FilterValidator.php
  8. 61
      framework/validators/NumberValidator.php
  9. 54
      framework/validators/RangeValidator.php
  10. 5
      framework/validators/RegularExpressionValidator.php
  11. 2
      framework/validators/RequiredValidator.php
  12. 88
      framework/validators/StringValidator.php
  13. 106
      framework/validators/TypeValidator.php
  14. 1
      framework/validators/UrlValidator.php
  15. 25
      framework/validators/Validator.php
  16. 2
      todo.txt

11
classmap.txt

@ -1,11 +0,0 @@
yii\
YiiBase
Yii
base\
Application
Behavior
Component
Event
Exception
Model
Module

26
framework/validators/BooleanValidator.php

@ -1,6 +1,6 @@
<?php <?php
/** /**
* CBooleanValidator class file. * BooleanValidator class file.
* *
* @link http://www.yiiframework.com/ * @link http://www.yiiframework.com/
* @copyright Copyright &copy; 2008-2012 Yii Software LLC * @copyright Copyright &copy; 2008-2012 Yii Software LLC
@ -10,14 +10,15 @@
namespace yii\validators; namespace yii\validators;
/** /**
* CBooleanValidator validates that the attribute value is either {@link trueValue} or {@link falseValue}. * BooleanValidator checks if the attribute value is a boolean value.
*
* Possible boolean values can be configured via the [[trueValue]] and [[falseValue]] properties.
* And the comparison can be either [[strict]] or not.
* *
* @author Qiang Xue <qiang.xue@gmail.com> * @author Qiang Xue <qiang.xue@gmail.com>
* @version $Id: CBooleanValidator.php 3120 2011-03-25 01:50:48Z qiang.xue $ * @since 2.0
* @package system.validators
* @since 1.0.10
*/ */
class CBooleanValidator extends Validator class BooleanValidator extends Validator
{ {
/** /**
* @var mixed the value representing true status. Defaults to '1'. * @var mixed the value representing true status. Defaults to '1'.
@ -28,8 +29,8 @@ class CBooleanValidator extends Validator
*/ */
public $falseValue = '0'; public $falseValue = '0';
/** /**
* @var boolean whether the comparison to {@link trueValue} and {@link falseValue} is strict. * @var boolean whether the comparison to [[trueValue]] and [[falseValue]] is strict.
* When this is true, the attribute value and type must both match those of {@link trueValue} or {@link falseValue}. * When this is true, the attribute value and type must both match those of [[trueValue]] or [[falseValue]].
* Defaults to false, meaning only the value needs to be matched. * Defaults to false, meaning only the value needs to be matched.
*/ */
public $strict = false; public $strict = false;
@ -48,11 +49,11 @@ class CBooleanValidator extends Validator
public function validateAttribute($object, $attribute) public function validateAttribute($object, $attribute)
{ {
$value = $object->$attribute; $value = $object->$attribute;
if ($this->allowEmpty && $this->isEmpty($value)) if ($this->allowEmpty && $this->isEmpty($value)) {
return; return;
}
if (!$this->strict && $value != $this->trueValue && $value != $this->falseValue if (!$this->strict && $value != $this->trueValue && $value != $this->falseValue
|| $this->strict && $value !== $this->trueValue && $value !== $this->falseValue) || $this->strict && $value !== $this->trueValue && $value !== $this->falseValue) {
{
$message = $this->message !== null ? $this->message : Yii::t('yii', '{attribute} must be either {true} or {false}.'); $message = $this->message !== null ? $this->message : Yii::t('yii', '{attribute} must be either {true} or {false}.');
$this->addError($object, $attribute, $message, array( $this->addError($object, $attribute, $message, array(
'{true}' => $this->trueValue, '{true}' => $this->trueValue,
@ -66,14 +67,13 @@ class CBooleanValidator extends Validator
* @param \yii\base\Model $object the data object being validated * @param \yii\base\Model $object the data object being validated
* @param string $attribute the name of the attribute to be validated. * @param string $attribute the name of the attribute to be validated.
* @return string the client-side validation script. * @return string the client-side validation script.
* @see CActiveForm::enableClientValidation
* @since 1.1.7
*/ */
public function clientValidateAttribute($object, $attribute) public function clientValidateAttribute($object, $attribute)
{ {
$message = $this->message !== null ? $this->message : Yii::t('yii', '{attribute} must be either {true} or {false}.'); $message = $this->message !== null ? $this->message : Yii::t('yii', '{attribute} must be either {true} or {false}.');
$message = strtr($message, array( $message = strtr($message, array(
'{attribute}' => $object->getAttributeLabel($attribute), '{attribute}' => $object->getAttributeLabel($attribute),
'{value}' => $object->$attribute,
'{true}' => $this->trueValue, '{true}' => $this->trueValue,
'{false}' => $this->falseValue, '{false}' => $this->falseValue,
)); ));

57
framework/validators/CaptchaValidator.php

@ -1,6 +1,6 @@
<?php <?php
/** /**
* CCaptchaValidator class file. * CaptchaValidator class file.
* *
* @link http://www.yiiframework.com/ * @link http://www.yiiframework.com/
* @copyright Copyright &copy; 2008-2012 Yii Software LLC * @copyright Copyright &copy; 2008-2012 Yii Software LLC
@ -10,25 +10,23 @@
namespace yii\validators; namespace yii\validators;
/** /**
* CCaptchaValidator validates that the attribute value is the same as the verification code displayed in the CAPTCHA. * CaptchaValidator validates that the attribute value is the same as the verification code displayed in the CAPTCHA.
* *
* CCaptchaValidator should be used together with {@link CCaptchaAction}. * CaptchaValidator should be used together with [[CaptchaAction]].
* *
* @author Qiang Xue <qiang.xue@gmail.com> * @author Qiang Xue <qiang.xue@gmail.com>
* @version $Id: CCaptchaValidator.php 3124 2011-03-25 15:48:05Z qiang.xue $ * @since 2.0
* @package system.validators
* @since 1.0
*/ */
class CCaptchaValidator extends Validator class CaptchaValidator extends Validator
{ {
/** /**
* @var boolean whether the comparison is case sensitive. Defaults to false. * @var boolean whether the comparison is case sensitive. Defaults to false.
*/ */
public $caseSensitive = false; public $caseSensitive = false;
/** /**
* @var string ID of the action that renders the CAPTCHA image. Defaults to 'captcha', * @var string the ID of the action that renders the CAPTCHA image. Defaults to 'captcha',
* meaning the 'captcha' action declared in the current controller. * meaning the `captcha` action declared in the current controller.
* This can also be a route consisting of controller ID and action ID. * This can also be a route consisting of controller ID and action ID (e.g. 'site/captcha').
*/ */
public $captchaAction = 'captcha'; public $captchaAction = 'captcha';
/** /**
@ -46,11 +44,11 @@ class CCaptchaValidator extends Validator
public function validateAttribute($object, $attribute) public function validateAttribute($object, $attribute)
{ {
$value = $object->$attribute; $value = $object->$attribute;
if ($this->allowEmpty && $this->isEmpty($value)) if ($this->allowEmpty && $this->isEmpty($value)) {
return; return;
}
$captcha = $this->getCaptchaAction(); $captcha = $this->getCaptchaAction();
if (!$captcha->validate($value, $this->caseSensitive)) if (!$captcha->validate($value, $this->caseSensitive)) {
{
$message = $this->message !== null ? $this->message : Yii::t('yii', 'The verification code is incorrect.'); $message = $this->message !== null ? $this->message : Yii::t('yii', 'The verification code is incorrect.');
$this->addError($object, $attribute, $message); $this->addError($object, $attribute, $message);
} }
@ -59,25 +57,24 @@ class CCaptchaValidator extends Validator
/** /**
* Returns the CAPTCHA action object. * Returns the CAPTCHA action object.
* @return CCaptchaAction the action object * @return CCaptchaAction the action object
* @since 1.1.7
*/ */
public function getCaptchaAction() public function getCaptchaAction()
{ {
if (($captcha = Yii::app()->getController()->createAction($this->captchaAction)) === null) if (strpos($this->captchaAction, '/') !== false) { // contains controller or module
{ $ca = Yii::app()->createController($this->captchaAction);
if (strpos($this->captchaAction, '/') !== false) // contains controller or module if ($ca !== null) {
{ list($controller, $actionID) = $ca;
if (($ca = Yii::app()->createController($this->captchaAction)) !== null) $action = $controller->createAction($actionID);
{
list($controller, $actionID) = $ca;
$captcha = $controller->createAction($actionID);
}
} }
if ($captcha === null)
throw new CException(Yii::t('yii', 'CCaptchaValidator.action "{id}" is invalid. Unable to find such an action in the current controller.',
array('{id}' => $this->captchaAction)));
} }
return $captcha; else {
$action = Yii::app()->getController()->createAction($this->captchaAction);
}
if ($action === null) {
throw new \yii\base\Exception('Invalid captcha action ID: ' . $this->captchaAction);
}
return $action;
} }
/** /**
@ -85,8 +82,6 @@ class CCaptchaValidator extends Validator
* @param \yii\base\Model $object the data object being validated * @param \yii\base\Model $object the data object being validated
* @param string $attribute the name of the attribute to be validated. * @param string $attribute the name of the attribute to be validated.
* @return string the client-side validation script. * @return string the client-side validation script.
* @see CActiveForm::enableClientValidation
* @since 1.1.7
*/ */
public function clientValidateAttribute($object, $attribute) public function clientValidateAttribute($object, $attribute)
{ {
@ -94,6 +89,7 @@ class CCaptchaValidator extends Validator
$message = $this->message !== null ? $this->message : Yii::t('yii', 'The verification code is incorrect.'); $message = $this->message !== null ? $this->message : Yii::t('yii', 'The verification code is incorrect.');
$message = strtr($message, array( $message = strtr($message, array(
'{attribute}' => $object->getAttributeLabel($attribute), '{attribute}' => $object->getAttributeLabel($attribute),
'{value}' => $object->$attribute,
)); ));
$code = $captcha->getVerifyCode(false); $code = $captcha->getVerifyCode(false);
$hash = $captcha->generateValidationHash($this->caseSensitive ? $code : strtolower($code)); $hash = $captcha->generateValidationHash($this->caseSensitive ? $code : strtolower($code));
@ -109,8 +105,7 @@ if(h != hash) {
} }
"; ";
if ($this->allowEmpty) if ($this->allowEmpty) {
{
$js = " $js = "
if($.trim(value)!='') { if($.trim(value)!='') {
$js $js

90
framework/validators/CompareValidator.php

@ -1,6 +1,6 @@
<?php <?php
/** /**
* CCompareValidator class file. * CompareValidator class file.
* *
* @link http://www.yiiframework.com/ * @link http://www.yiiframework.com/
* @copyright Copyright &copy; 2008-2012 Yii Software LLC * @copyright Copyright &copy; 2008-2012 Yii Software LLC
@ -10,26 +10,24 @@
namespace yii\validators; namespace yii\validators;
/** /**
* CCompareValidator compares the specified attribute value with another value and validates if they are equal. * CompareValidator compares the specified attribute value with another value and validates if they are equal.
* *
* The value being compared with can be another attribute value * The value being compared with can be another attribute value
* (specified via {@link compareAttribute}) or a constant (specified via * (specified via [[compareAttribute]]) or a constant (specified via
* {@link compareValue}. When both are specified, the latter takes * [[compareValue]]. When both are specified, the latter takes
* precedence. If neither is specified, the attribute will be compared * precedence. If neither is specified, the attribute will be compared
* with another attribute whose name is by appending "_repeat" to the source * with another attribute whose name is by appending "_repeat" to the source
* attribute name. * attribute name.
* *
* The comparison can be either {@link strict} or not. * The comparison can be either [[strict]] or not.
* *
* Starting from version 1.0.8, CCompareValidator supports different comparison operators. * CompareValidator supports different comparison operators, specified
* Previously, it only compares to see if two values are equal or not. * via the [[operator]] property.
* *
* @author Qiang Xue <qiang.xue@gmail.com> * @author Qiang Xue <qiang.xue@gmail.com>
* @version $Id: CCompareValidator.php 3120 2011-03-25 01:50:48Z qiang.xue $ * @since 2.0
* @package system.validators
* @since 1.0
*/ */
class CCompareValidator extends Validator class CompareValidator extends Validator
{ {
/** /**
* @var string the name of the attribute to be compared with * @var string the name of the attribute to be compared with
@ -53,16 +51,15 @@ class CCompareValidator extends Validator
* @var string the operator for comparison. Defaults to '='. * @var string the operator for comparison. Defaults to '='.
* The followings are valid operators: * The followings are valid operators:
* <ul> * <ul>
* <li>'=' or '==': validates to see if the two values are equal. If {@link strict} is true, the comparison * <li>'=' or '==': validates to see if the two values are equal. If [[strict]] is true, the comparison
* will be done in strict mode (i.e. checking value type as well).</li> * will be done in strict mode (i.e. checking value type as well).</li>
* <li>'!=': validates to see if the two values are NOT equal. If {@link strict} is true, the comparison * <li>'!=': validates to see if the two values are NOT equal. If [[strict]] is true, the comparison
* will be done in strict mode (i.e. checking value type as well).</li> * will be done in strict mode (i.e. checking value type as well).</li>
* <li>'>': validates to see if the value being validated is greater than the value being compared with.</li> * <li>'>': validates to see if the value being validated is greater than the value being compared with.</li>
* <li>'>=': validates to see if the value being validated is greater than or equal to the value being compared with.</li> * <li>'>=': validates to see if the value being validated is greater than or equal to the value being compared with.</li>
* <li>'<': validates to see if the value being validated is less than the value being compared with.</li> * <li>'<': validates to see if the value being validated is less than the value being compared with.</li>
* <li>'<=': validates to see if the value being validated is less than or equal to the value being compared with.</li> * <li>'<=': validates to see if the value being validated is less than or equal to the value being compared with.</li>
* </ul> * </ul>
* @since 1.0.8
*/ */
public $operator = '='; public $operator = '=';
@ -75,64 +72,58 @@ class CCompareValidator extends Validator
public function validateAttribute($object, $attribute) public function validateAttribute($object, $attribute)
{ {
$value = $object->$attribute; $value = $object->$attribute;
if ($this->allowEmpty && $this->isEmpty($value)) if ($this->allowEmpty && $this->isEmpty($value)) {
return; return;
if ($this->compareValue !== null) }
if ($this->compareValue !== null) {
$compareTo = $compareValue = $this->compareValue; $compareTo = $compareValue = $this->compareValue;
else }
{ else {
$compareAttribute = $this->compareAttribute === null ? $attribute . '_repeat' : $this->compareAttribute; $compareAttribute = $this->compareAttribute === null ? $attribute . '_repeat' : $this->compareAttribute;
$compareValue = $object->$compareAttribute; $compareValue = $object->$compareAttribute;
$compareTo = $object->getAttributeLabel($compareAttribute); $compareTo = $object->getAttributeLabel($compareAttribute);
} }
switch ($this->operator) switch ($this->operator) {
{
case '=': case '=':
case '==': case '==':
if (($this->strict && $value !== $compareValue) || (!$this->strict && $value != $compareValue)) if (($this->strict && $value !== $compareValue) || (!$this->strict && $value != $compareValue)) {
{
$message = $this->message !== null ? $this->message : Yii::t('yii', '{attribute} must be repeated exactly.'); $message = $this->message !== null ? $this->message : Yii::t('yii', '{attribute} must be repeated exactly.');
$this->addError($object, $attribute, $message, array('{compareAttribute}' => $compareTo)); $this->addError($object, $attribute, $message, array('{compareAttribute}' => $compareTo));
} }
break; break;
case '!=': case '!=':
if (($this->strict && $value === $compareValue) || (!$this->strict && $value == $compareValue)) if (($this->strict && $value === $compareValue) || (!$this->strict && $value == $compareValue)) {
{
$message = $this->message !== null ? $this->message : Yii::t('yii', '{attribute} must not be equal to "{compareValue}".'); $message = $this->message !== null ? $this->message : Yii::t('yii', '{attribute} must not be equal to "{compareValue}".');
$this->addError($object, $attribute, $message, array('{compareAttribute}' => $compareTo, '{compareValue}' => $compareValue)); $this->addError($object, $attribute, $message, array('{compareAttribute}' => $compareTo, '{compareValue}' => $compareValue));
} }
break; break;
case '>': case '>':
if ($value <= $compareValue) if ($value <= $compareValue) {
{
$message = $this->message !== null ? $this->message : Yii::t('yii', '{attribute} must be greater than "{compareValue}".'); $message = $this->message !== null ? $this->message : Yii::t('yii', '{attribute} must be greater than "{compareValue}".');
$this->addError($object, $attribute, $message, array('{compareAttribute}' => $compareTo, '{compareValue}' => $compareValue)); $this->addError($object, $attribute, $message, array('{compareAttribute}' => $compareTo, '{compareValue}' => $compareValue));
} }
break; break;
case '>=': case '>=':
if ($value < $compareValue) if ($value < $compareValue) {
{
$message = $this->message !== null ? $this->message : Yii::t('yii', '{attribute} must be greater than or equal to "{compareValue}".'); $message = $this->message !== null ? $this->message : Yii::t('yii', '{attribute} must be greater than or equal to "{compareValue}".');
$this->addError($object, $attribute, $message, array('{compareAttribute}' => $compareTo, '{compareValue}' => $compareValue)); $this->addError($object, $attribute, $message, array('{compareAttribute}' => $compareTo, '{compareValue}' => $compareValue));
} }
break; break;
case '<': case '<':
if ($value >= $compareValue) if ($value >= $compareValue) {
{
$message = $this->message !== null ? $this->message : Yii::t('yii', '{attribute} must be less than "{compareValue}".'); $message = $this->message !== null ? $this->message : Yii::t('yii', '{attribute} must be less than "{compareValue}".');
$this->addError($object, $attribute, $message, array('{compareAttribute}' => $compareTo, '{compareValue}' => $compareValue)); $this->addError($object, $attribute, $message, array('{compareAttribute}' => $compareTo, '{compareValue}' => $compareValue));
} }
break; break;
case '<=': case '<=':
if ($value > $compareValue) if ($value > $compareValue) {
{
$message = $this->message !== null ? $this->message : Yii::t('yii', '{attribute} must be less than or equal to "{compareValue}".'); $message = $this->message !== null ? $this->message : Yii::t('yii', '{attribute} must be less than or equal to "{compareValue}".');
$this->addError($object, $attribute, $message, array('{compareAttribute}' => $compareTo, '{compareValue}' => $compareValue)); $this->addError($object, $attribute, $message, array('{compareAttribute}' => $compareTo, '{compareValue}' => $compareValue));
} }
break; break;
default: default:
throw new CException(Yii::t('yii', 'Invalid operator "{operator}".', array('{operator}' => $this->operator))); throw new \yii\base\Exception('Invalid operator "' . $this->operator . '".');
} }
} }
@ -141,59 +132,60 @@ class CCompareValidator extends Validator
* @param \yii\base\Model $object the data object being validated * @param \yii\base\Model $object the data object being validated
* @param string $attribute the name of the attribute to be validated. * @param string $attribute the name of the attribute to be validated.
* @return string the client-side validation script. * @return string the client-side validation script.
* @see CActiveForm::enableClientValidation
* @since 1.1.7
*/ */
public function clientValidateAttribute($object, $attribute) public function clientValidateAttribute($object, $attribute)
{ {
if ($this->compareValue !== null) if ($this->compareValue !== null) {
{
$compareTo = $this->compareValue; $compareTo = $this->compareValue;
$compareValue = json_encode($this->compareValue); $compareValue = json_encode($this->compareValue);
} }
else else {
{
$compareAttribute = $this->compareAttribute === null ? $attribute . '_repeat' : $this->compareAttribute; $compareAttribute = $this->compareAttribute === null ? $attribute . '_repeat' : $this->compareAttribute;
$compareValue = "\$('#" . (CHtml::activeId($object, $compareAttribute)) . "').val()"; $compareValue = "\$('#" . (CHtml::activeId($object, $compareAttribute)) . "').val()";
$compareTo = $object->getAttributeLabel($compareAttribute); $compareTo = $object->getAttributeLabel($compareAttribute);
} }
$message = $this->message; $message = $this->message;
switch ($this->operator) switch ($this->operator) {
{
case '=': case '=':
case '==': case '==':
if ($message === null) if ($message === null) {
$message = Yii::t('yii', '{attribute} must be repeated exactly.'); $message = Yii::t('yii', '{attribute} must be repeated exactly.');
}
$condition = 'value!=' . $compareValue; $condition = 'value!=' . $compareValue;
break; break;
case '!=': case '!=':
if ($message === null) if ($message === null) {
$message = Yii::t('yii', '{attribute} must not be equal to "{compareValue}".'); $message = Yii::t('yii', '{attribute} must not be equal to "{compareValue}".');
}
$condition = 'value==' . $compareValue; $condition = 'value==' . $compareValue;
break; break;
case '>': case '>':
if ($message === null) if ($message === null) {
$message = Yii::t('yii', '{attribute} must be greater than "{compareValue}".'); $message = Yii::t('yii', '{attribute} must be greater than "{compareValue}".');
}
$condition = 'value<=' . $compareValue; $condition = 'value<=' . $compareValue;
break; break;
case '>=': case '>=':
if ($message === null) if ($message === null) {
$message = Yii::t('yii', '{attribute} must be greater than or equal to "{compareValue}".'); $message = Yii::t('yii', '{attribute} must be greater than or equal to "{compareValue}".');
}
$condition = 'value<' . $compareValue; $condition = 'value<' . $compareValue;
break; break;
case '<': case '<':
if ($message === null) if ($message === null) {
$message = Yii::t('yii', '{attribute} must be less than "{compareValue}".'); $message = Yii::t('yii', '{attribute} must be less than "{compareValue}".');
}
$condition = 'value>=' . $compareValue; $condition = 'value>=' . $compareValue;
break; break;
case '<=': case '<=':
if ($message === null) if ($message === null) {
$message = Yii::t('yii', '{attribute} must be less than or equal to "{compareValue}".'); $message = Yii::t('yii', '{attribute} must be less than or equal to "{compareValue}".');
}
$condition = 'value>' . $compareValue; $condition = 'value>' . $compareValue;
break; break;
default: default:
throw new CException(Yii::t('yii', 'Invalid operator "{operator}".', array('{operator}' => $this->operator))); throw new \yii\base\Exception('Invalid operator "' . $this->operator . '".');
} }
$message = strtr($message, array( $message = strtr($message, array(
@ -202,7 +194,7 @@ class CCompareValidator extends Validator
)); ));
return " return "
if(" . ($this->allowEmpty ? "$.trim(value)!='' && " : '') . $condition . ") { if (" . ($this->allowEmpty ? "$.trim(value)!='' && " : '') . $condition . ") {
messages.push(" . json_encode($message) . "); messages.push(" . json_encode($message) . ");
} }
"; ";

30
framework/validators/DefaultValueValidator.php

@ -1,6 +1,6 @@
<?php <?php
/** /**
* CDefaultValueValidator class file. * DefaultValueValidator class file.
* *
* @link http://www.yiiframework.com/ * @link http://www.yiiframework.com/
* @copyright Copyright &copy; 2008-2012 Yii Software LLC * @copyright Copyright &copy; 2008-2012 Yii Software LLC
@ -10,25 +10,28 @@
namespace yii\validators; namespace yii\validators;
/** /**
* CDefaultValueValidator sets the attributes with the specified value. * DefaultValueValidator sets the attribute to be the specified default value.
* It does not do validation. Its existence is mainly to allow *
* By default, when the attribute being validated is [[isEmpty|empty]], the validator
* will assign a default [[value]] to it. However, if [[setOnEmpty]] is false, the validator
* will always assign the default [[value]] to the attribute, no matter it is empty or not.
*
* DefaultValueValidator is not really a validator. It is provided mainly to allow
* specifying attribute default values in a dynamic way. * specifying attribute default values in a dynamic way.
* *
* @author Qiang Xue <qiang.xue@gmail.com> * @author Qiang Xue <qiang.xue@gmail.com>
* @version $Id: CDefaultValueValidator.php 2799 2011-01-01 19:31:13Z qiang.xue $ * @since 2.0
* @package system.validators
* @since 1.0.2
*/ */
class CDefaultValueValidator extends Validator class DefaultValueValidator extends Validator
{ {
/** /**
* @var mixed the default value to be set to the specified attributes. * @var mixed the default value to be set to the specified attributes.
*/ */
public $value; public $value;
/** /**
* @var boolean whether to set the default value only when the attribute value is null or empty string. * @var boolean whether to set the default [[value]] only when the attribute is [[isEmpty|empty]].
* Defaults to true. If false, the attribute will always be assigned with the default value, * Defaults to true. If false, the attribute will always be assigned with the default [[value]],
* even if it is already explicitly assigned a value. * no matter it is empty or not.
*/ */
public $setOnEmpty = true; public $setOnEmpty = true;
@ -39,13 +42,8 @@ class CDefaultValueValidator extends Validator
*/ */
public function validateAttribute($object, $attribute) public function validateAttribute($object, $attribute)
{ {
if (!$this->setOnEmpty) if (!$this->setOnEmpty || $this->isEmpty($object->$attribute)) {
$object->$attribute = $this->value; $object->$attribute = $this->value;
else
{
$value = $object->$attribute;
if ($value === null || $value === '')
$object->$attribute = $this->value;
} }
} }
} }

1
framework/validators/EmailValidator.php

@ -102,6 +102,7 @@ class EmailValidator extends Validator
$message = $this->message !== null ? $this->message : Yii::t('yii', '{attribute} is not a valid email address.'); $message = $this->message !== null ? $this->message : Yii::t('yii', '{attribute} is not a valid email address.');
$message = strtr($message, array( $message = strtr($message, array(
'{attribute}' => $object->getAttributeLabel($attribute), '{attribute}' => $object->getAttributeLabel($attribute),
'{value}' => $object->$attribute,
)); ));
$condition = "!value.match( {$this->pattern})"; $condition = "!value.match( {$this->pattern})";

42
framework/validators/FilterValidator.php

@ -1,6 +1,6 @@
<?php <?php
/** /**
* CFilterValidator class file. * FilterValidator class file.
* *
* @link http://www.yiiframework.com/ * @link http://www.yiiframework.com/
* @copyright Copyright &copy; 2008-2012 Yii Software LLC * @copyright Copyright &copy; 2008-2012 Yii Software LLC
@ -10,28 +10,33 @@
namespace yii\validators; namespace yii\validators;
/** /**
* CFilterValidator transforms the data being validated based on a filter. * FilterValidator converts the attribute value according to a filter.
* *
* CFilterValidator is actually not a validator but a data processor. * FilterValidator is actually not a validator but a data processor.
* It invokes the specified filter method to process the attribute value * It invokes the specified filter callback to process the attribute value
* and save the processed value back to the attribute. The filter method * and save the processed value back to the attribute. The filter must be
* must follow the following signature: * a valid PHP callback with the following signature:
* <pre> *
* ~~~
* function foo($value) {...return $newValue; } * function foo($value) {...return $newValue; }
* </pre> * ~~~
* Many PHP functions qualify this signature (e.g. trim). *
* Many PHP functions qualify this signature (e.g. `trim()`).
* *
* To specify the filter method, set {@link filter} property to be the function name. * To specify the filter, set [[filter]] property to be the callback.
* *
* @author Qiang Xue <qiang.xue@gmail.com> * @author Qiang Xue <qiang.xue@gmail.com>
* @version $Id: CFilterValidator.php 2799 2011-01-01 19:31:13Z qiang.xue $ * @since 2.0
* @package system.validators
* @since 1.0
*/ */
class CFilterValidator extends Validator class FilterValidator extends Validator
{ {
/** /**
* @var callback the filter method * @var callback the filter. This can be a global function name, anonymous function, etc.
* The function signature must be as follows,
*
* ~~~
* function foo($value) {...return $newValue; }
* ~~~
*/ */
public $filter; public $filter;
@ -43,8 +48,9 @@ class CFilterValidator extends Validator
*/ */
public function validateAttribute($object, $attribute) public function validateAttribute($object, $attribute)
{ {
if ($this->filter === null || !is_callable($this->filter)) if ($this->filter === null) {
throw new CException(Yii::t('yii', 'The "filter" property must be specified with a valid callback.')); throw new \yii\base\Exception('The "filter" property must be specified with a valid callback.');
$object->$attribute = call_user_func_array($this->filter, array($object->$attribute)); }
$object->$attribute = call_user_func($this->filter, $object->$attribute);
} }
} }

61
framework/validators/NumberValidator.php

@ -1,6 +1,6 @@
<?php <?php
/** /**
* CNumberValidator class file. * NumberValidator class file.
* *
* @link http://www.yiiframework.com/ * @link http://www.yiiframework.com/
* @copyright Copyright &copy; 2008-2012 Yii Software LLC * @copyright Copyright &copy; 2008-2012 Yii Software LLC
@ -10,14 +10,12 @@
namespace yii\validators; namespace yii\validators;
/** /**
* CNumberValidator validates that the attribute value is a number. * NumberValidator validates that the attribute value is a number.
* *
* @author Qiang Xue <qiang.xue@gmail.com> * @author Qiang Xue <qiang.xue@gmail.com>
* @version $Id: CNumberValidator.php 3190 2011-04-16 23:40:21Z qiang.xue $ * @since 2.0
* @package system.validators
* @since 1.0
*/ */
class CNumberValidator extends Validator class NumberValidator extends Validator
{ {
/** /**
* @var boolean whether the attribute value can only be an integer. Defaults to false. * @var boolean whether the attribute value can only be an integer. Defaults to false.
@ -37,21 +35,19 @@ class CNumberValidator extends Validator
*/ */
public $min; public $min;
/** /**
* @var string user-defined error message used when the value is too big. * @var string user-defined error message used when the value is bigger than [[max]].
*/ */
public $tooBig; public $tooBig;
/** /**
* @var string user-defined error message used when the value is too small. * @var string user-defined error message used when the value is smaller than [[min]].
*/ */
public $tooSmall; public $tooSmall;
/** /**
* @var string the regular expression for matching integers. * @var string the regular expression for matching integers.
* @since 1.1.7
*/ */
public $integerPattern = '/^\s*[+-]?\d+\s*$/'; public $integerPattern = '/^\s*[+-]?\d+\s*$/';
/** /**
* @var string the regular expression for matching numbers. * @var string the regular expression for matching numbers.
* @since 1.1.7
*/ */
public $numberPattern = '/^\s*[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?\s*$/'; public $numberPattern = '/^\s*[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?\s*$/';
@ -65,31 +61,26 @@ class CNumberValidator extends Validator
public function validateAttribute($object, $attribute) public function validateAttribute($object, $attribute)
{ {
$value = $object->$attribute; $value = $object->$attribute;
if ($this->allowEmpty && $this->isEmpty($value)) if ($this->allowEmpty && $this->isEmpty($value)) {
return; return;
if ($this->integerOnly) }
{ if ($this->integerOnly) {
if (!preg_match($this->integerPattern, "$value")) if (!preg_match($this->integerPattern, "$value")) {
{
$message = $this->message !== null ? $this->message : Yii::t('yii', '{attribute} must be an integer.'); $message = $this->message !== null ? $this->message : Yii::t('yii', '{attribute} must be an integer.');
$this->addError($object, $attribute, $message); $this->addError($object, $attribute, $message);
} }
} }
else else {
{ if (!preg_match($this->numberPattern, "$value")) {
if (!preg_match($this->numberPattern, "$value"))
{
$message = $this->message !== null ? $this->message : Yii::t('yii', '{attribute} must be a number.'); $message = $this->message !== null ? $this->message : Yii::t('yii', '{attribute} must be a number.');
$this->addError($object, $attribute, $message); $this->addError($object, $attribute, $message);
} }
} }
if ($this->min !== null && $value < $this->min) if ($this->min !== null && $value < $this->min) {
{
$message = $this->tooSmall !== null ? $this->tooSmall : Yii::t('yii', '{attribute} is too small (minimum is {min}).'); $message = $this->tooSmall !== null ? $this->tooSmall : Yii::t('yii', '{attribute} is too small (minimum is {min}).');
$this->addError($object, $attribute, $message, array('{min}' => $this->min)); $this->addError($object, $attribute, $message, array('{min}' => $this->min));
} }
if ($this->max !== null && $value > $this->max) if ($this->max !== null && $value > $this->max) {
{
$message = $this->tooBig !== null ? $this->tooBig : Yii::t('yii', '{attribute} is too big (maximum is {max}).'); $message = $this->tooBig !== null ? $this->tooBig : Yii::t('yii', '{attribute} is too big (maximum is {max}).');
$this->addError($object, $attribute, $message, array('{max}' => $this->max)); $this->addError($object, $attribute, $message, array('{max}' => $this->max));
} }
@ -100,30 +91,35 @@ class CNumberValidator extends Validator
* @param \yii\base\Model $object the data object being validated * @param \yii\base\Model $object the data object being validated
* @param string $attribute the name of the attribute to be validated. * @param string $attribute the name of the attribute to be validated.
* @return string the client-side validation script. * @return string the client-side validation script.
* @see CActiveForm::enableClientValidation
* @since 1.1.7
*/ */
public function clientValidateAttribute($object, $attribute) public function clientValidateAttribute($object, $attribute)
{ {
$label = $object->getAttributeLabel($attribute); $label = $object->getAttributeLabel($attribute);
$value = $object->$attribute;
if (($message = $this->message) === null) if (($message = $this->message) === null) {
$message = $this->integerOnly ? Yii::t('yii', '{attribute} must be an integer.') : Yii::t('yii', '{attribute} must be a number.'); $message = $this->integerOnly ? Yii::t('yii', '{attribute} must be an integer.') : Yii::t('yii', '{attribute} must be a number.');
}
$message = strtr($message, array( $message = strtr($message, array(
'{attribute}' => $label, '{attribute}' => $label,
'{value}' => $value,
)); ));
if (($tooBig = $this->tooBig) === null) if (($tooBig = $this->tooBig) === null) {
$tooBig = Yii::t('yii', '{attribute} is too big (maximum is {max}).'); $tooBig = Yii::t('yii', '{attribute} is too big (maximum is {max}).');
}
$tooBig = strtr($tooBig, array( $tooBig = strtr($tooBig, array(
'{attribute}' => $label, '{attribute}' => $label,
'{value}' => $value,
'{max}' => $this->max, '{max}' => $this->max,
)); ));
if (($tooSmall = $this->tooSmall) === null) if (($tooSmall = $this->tooSmall) === null) {
$tooSmall = Yii::t('yii', '{attribute} is too small (minimum is {min}).'); $tooSmall = Yii::t('yii', '{attribute} is too small (minimum is {min}).');
}
$tooSmall = strtr($tooSmall, array( $tooSmall = strtr($tooSmall, array(
'{attribute}' => $label, '{attribute}' => $label,
'{value}' => $value,
'{min}' => $this->min, '{min}' => $this->min,
)); ));
@ -133,16 +129,14 @@ if(!value.match($pattern)) {
messages.push(" . json_encode($message) . "); messages.push(" . json_encode($message) . ");
} }
"; ";
if ($this->min !== null) if ($this->min !== null) {
{
$js .= " $js .= "
if(value< {$this->min}) { if(value< {$this->min}) {
messages.push(" . json_encode($tooSmall) . "); messages.push(" . json_encode($tooSmall) . ");
} }
"; ";
} }
if ($this->max !== null) if ($this->max !== null) {
{
$js .= " $js .= "
if(value> {$this->max}) { if(value> {$this->max}) {
messages.push(" . json_encode($tooBig) . "); messages.push(" . json_encode($tooBig) . ");
@ -150,8 +144,7 @@ if(value> {$this->max}) {
"; ";
} }
if ($this->allowEmpty) if ($this->allowEmpty) {
{
$js = " $js = "
if($.trim(value)!='') { if($.trim(value)!='') {
$js $js

54
framework/validators/RangeValidator.php

@ -1,6 +1,6 @@
<?php <?php
/** /**
* CRangeValidator class file. * RangeValidator class file.
* *
* @link http://www.yiiframework.com/ * @link http://www.yiiframework.com/
* @copyright Copyright &copy; 2008-2012 Yii Software LLC * @copyright Copyright &copy; 2008-2012 Yii Software LLC
@ -10,15 +10,16 @@
namespace yii\validators; namespace yii\validators;
/** /**
* CRangeValidator validates that the attribute value is among the list (specified via {@link range}). * RangeValidator validates that the attribute value is among a list of values.
* You may invert the validation logic with help of the {@link not} property (available since 1.1.5). *
* The range can be specified via the [[range]] property.
* If the [[not]] property is set true, the validator will ensure the attribute value
* is NOT among the specified range.
* *
* @author Qiang Xue <qiang.xue@gmail.com> * @author Qiang Xue <qiang.xue@gmail.com>
* @version $Id: CRangeValidator.php 3120 2011-03-25 01:50:48Z qiang.xue $ * @since 2.0
* @package system.validators
* @since 1.0
*/ */
class CRangeValidator extends Validator class RangeValidator extends Validator
{ {
/** /**
* @var array list of valid values that the attribute value should be among * @var array list of valid values that the attribute value should be among
@ -35,8 +36,7 @@ class CRangeValidator extends Validator
public $allowEmpty = true; public $allowEmpty = true;
/** /**
* @var boolean whether to invert the validation logic. Defaults to false. If set to true, * @var boolean whether to invert the validation logic. Defaults to false. If set to true,
* the attribute value should NOT be among the list of values defined via {@link range}. * the attribute value should NOT be among the list of values defined via [[range]].
* @since 1.1.5
**/ **/
public $not = false; public $not = false;
@ -49,18 +49,18 @@ class CRangeValidator extends Validator
public function validateAttribute($object, $attribute) public function validateAttribute($object, $attribute)
{ {
$value = $object->$attribute; $value = $object->$attribute;
if ($this->allowEmpty && $this->isEmpty($value)) if ($this->allowEmpty && $this->isEmpty($value)) {
return; return;
if (!is_array($this->range)) }
throw new CException(Yii::t('yii', 'The "range" property must be specified with a list of values.')); if (!is_array($this->range)) {
if (!$this->not && !in_array($value, $this->range, $this->strict)) throw new \yii\base\Exception('The "range" property must be specified as an array.');
{ }
$message = $this->message !== null ? $this->message : Yii::t('yii', '{attribute} is not in the list.'); if (!$this->not && !in_array($value, $this->range, $this->strict)) {
$message = $this->message !== null ? $this->message : Yii::t('yii', '{attribute} should be in the list.');
$this->addError($object, $attribute, $message); $this->addError($object, $attribute, $message);
} }
elseif ($this->not && in_array($value, $this->range, $this->strict)) elseif ($this->not && in_array($value, $this->range, $this->strict)) {
{ $message = $this->message !== null ? $this->message : Yii::t('yii', '{attribute} should NOT be in the list.');
$message = $this->message !== null ? $this->message : Yii::t('yii', '{attribute} is in the list.');
$this->addError($object, $attribute, $message); $this->addError($object, $attribute, $message);
} }
} }
@ -70,27 +70,29 @@ class CRangeValidator extends Validator
* @param \yii\base\Model $object the data object being validated * @param \yii\base\Model $object the data object being validated
* @param string $attribute the name of the attribute to be validated. * @param string $attribute the name of the attribute to be validated.
* @return string the client-side validation script. * @return string the client-side validation script.
* @see CActiveForm::enableClientValidation
* @since 1.1.7
*/ */
public function clientValidateAttribute($object, $attribute) public function clientValidateAttribute($object, $attribute)
{ {
if (!is_array($this->range)) if (!is_array($this->range)) {
throw new CException(Yii::t('yii', 'The "range" property must be specified with a list of values.')); throw new \yii\base\Exception('The "range" property must be specified as an array.');
}
if (($message = $this->message) === null) if (($message = $this->message) === null) {
$message = $this->not ? Yii::t('yii', '{attribute} is in the list.') : Yii::t('yii', '{attribute} is not in the list.'); $message = $this->not ? Yii::t('yii', '{attribute} should NOT be in the list.') : Yii::t('yii', '{attribute} should be in the list.');
}
$message = strtr($message, array( $message = strtr($message, array(
'{attribute}' => $object->getAttributeLabel($attribute), '{attribute}' => $object->getAttributeLabel($attribute),
'{value}' => $object->$attribute,
)); ));
$range = array(); $range = array();
foreach ($this->range as $value) foreach ($this->range as $value) {
$range[] = (string)$value; $range[] = (string)$value;
}
$range = json_encode($range); $range = json_encode($range);
return " return "
if(" . ($this->allowEmpty ? "$.trim(value)!='' && " : '') . ($this->not ? "$.inArray(value, $range)>=0" : "$.inArray(value, $range)<0") . ") { if (" . ($this->allowEmpty ? "$.trim(value)!='' && " : '') . ($this->not ? "$.inArray(value, $range)>=0" : "$.inArray(value, $range)<0") . ") {
messages.push(" . json_encode($message) . "); messages.push(" . json_encode($message) . ");
} }
"; ";

5
framework/validators/RegularExpressionValidator.php

@ -12,7 +12,7 @@ namespace yii\validators;
/** /**
* RegularExpressionValidator validates that the attribute value matches the specified [[pattern]]. * RegularExpressionValidator validates that the attribute value matches the specified [[pattern]].
* *
* If [[not]] is set true, the validator will ensure the attribute value do NOT match the [[pattern]]. * If the [[not]] property is set true, the validator will ensure the attribute value do NOT match the [[pattern]].
* *
* @author Qiang Xue <qiang.xue@gmail.com> * @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0 * @since 2.0
@ -64,12 +64,13 @@ class RegularExpressionValidator extends Validator
public function clientValidateAttribute($object, $attribute) public function clientValidateAttribute($object, $attribute)
{ {
if ($this->pattern === null) { if ($this->pattern === null) {
throw new \yii\base\Exception(Yii::t('yii', 'The "pattern" property must be specified with a valid regular expression.')); throw new \yii\base\Exception('The "pattern" property must be specified with a valid regular expression.');
} }
$message = $this->message !== null ? $this->message : Yii::t('yii', '{attribute} is invalid.'); $message = $this->message !== null ? $this->message : Yii::t('yii', '{attribute} is invalid.');
$message = strtr($message, array( $message = strtr($message, array(
'{attribute}' => $object->getAttributeLabel($attribute), '{attribute}' => $object->getAttributeLabel($attribute),
'{value}' => $object->$attribute,
)); ));
$pattern = $this->pattern; $pattern = $this->pattern;

2
framework/validators/RequiredValidator.php

@ -75,6 +75,7 @@ class RequiredValidator extends Validator
} }
$message = strtr($message, array( $message = strtr($message, array(
'{attribute}' => $object->getAttributeLabel($attribute), '{attribute}' => $object->getAttributeLabel($attribute),
'{value}' => $object->$attribute,
'{requiredValue}' => $this->requiredValue, '{requiredValue}' => $this->requiredValue,
)); ));
return " return "
@ -89,6 +90,7 @@ if (value != " . json_encode($this->requiredValue) . ") {
} }
$message = strtr($message, array( $message = strtr($message, array(
'{attribute}' => $object->getAttributeLabel($attribute), '{attribute}' => $object->getAttributeLabel($attribute),
'{value}' => $object->$attribute,
)); ));
return " return "
if($.trim(value) == '') { if($.trim(value) == '') {

88
framework/validators/StringValidator.php

@ -1,6 +1,6 @@
<?php <?php
/** /**
* CStringValidator class file. * StringValidator class file.
* *
* @link http://www.yiiframework.com/ * @link http://www.yiiframework.com/
* @copyright Copyright &copy; 2008-2012 Yii Software LLC * @copyright Copyright &copy; 2008-2012 Yii Software LLC
@ -10,16 +10,14 @@
namespace yii\validators; namespace yii\validators;
/** /**
* CStringValidator validates that the attribute value is of certain length. * StringValidator validates that the attribute value is of certain length.
* *
* Note, this validator should only be used with string-typed attributes. * Note, this validator should only be used with string-typed attributes.
* *
* @author Qiang Xue <qiang.xue@gmail.com> * @author Qiang Xue <qiang.xue@gmail.com>
* @version $Id: CStringValidator.php 3148 2011-03-31 21:44:00Z alexander.makarow $ * @since 2.0
* @package system.validators
* @since 1.0
*/ */
class CStringValidator extends Validator class StringValidator extends Validator
{ {
/** /**
* @var integer maximum length. Defaults to null, meaning no maximum limit. * @var integer maximum length. Defaults to null, meaning no maximum limit.
@ -34,26 +32,33 @@ class CStringValidator extends Validator
*/ */
public $is; public $is;
/** /**
* @var string user-defined error message used when the value is too short. * @var string user-defined error message used when the value is not a string
*/
public $message;
/**
* @var string user-defined error message used when the length of the value is smaller than [[min]].
*/ */
public $tooShort; public $tooShort;
/** /**
* @var string user-defined error message used when the value is too long. * @var string user-defined error message used when the length of the value is greater than [[max]].
*/ */
public $tooLong; public $tooLong;
/** /**
* @var string user-defined error message used when the length of the value is not equal to [[is]].
*/
public $notEqual;
/**
* @var boolean whether the attribute value can be null or empty. Defaults to true, * @var boolean whether the attribute value can be null or empty. Defaults to true,
* meaning that if the attribute is empty, it is considered valid. * meaning that if the attribute is empty, it is considered valid.
*/ */
public $allowEmpty = true; public $allowEmpty = true;
/** /**
* @var string the encoding of the string value to be validated (e.g. 'UTF-8'). * @var mixed the encoding of the string value to be validated (e.g. 'UTF-8').
* This property is used only when mbstring PHP extension is enabled. * This property is used only when mbstring PHP extension is enabled.
* The value of this property will be used as the 2nd parameter of the * The value of this property will be used as the 2nd parameter of the
* mb_strlen() function. If this property is not set, the application charset * mb_strlen() function. If this property is not set, the application charset
* will be used. * will be used. If this property is set false, then strlen() will be used even
* If this property is set false, then strlen() will be used even if mbstring is enabled. * if mbstring is enabled.
* @since 1.1.1
*/ */
public $encoding; public $encoding;
@ -66,27 +71,33 @@ class CStringValidator extends Validator
public function validateAttribute($object, $attribute) public function validateAttribute($object, $attribute)
{ {
$value = $object->$attribute; $value = $object->$attribute;
if ($this->allowEmpty && $this->isEmpty($value)) if ($this->allowEmpty && $this->isEmpty($value)) {
return;
}
if (!is_string($value)) {
$message = $this->message !== null ? $this->message : Yii::t('yii', '{attribute} must be a string.');
$this->addError($object, $attribute, $message);
return; return;
}
if (function_exists('mb_strlen') && $this->encoding !== false) if (function_exists('mb_strlen') && $this->encoding !== false) {
$length = mb_strlen($value, $this->encoding ? $this->encoding : Yii::app()->charset); $length = mb_strlen($value, $this->encoding ? $this->encoding : Yii::app()->charset);
else }
else {
$length = strlen($value); $length = strlen($value);
}
if ($this->min !== null && $length < $this->min) if ($this->min !== null && $length < $this->min) {
{
$message = $this->tooShort !== null ? $this->tooShort : Yii::t('yii', '{attribute} is too short (minimum is {min} characters).'); $message = $this->tooShort !== null ? $this->tooShort : Yii::t('yii', '{attribute} is too short (minimum is {min} characters).');
$this->addError($object, $attribute, $message, array('{min}' => $this->min)); $this->addError($object, $attribute, $message, array('{min}' => $this->min));
} }
if ($this->max !== null && $length > $this->max) if ($this->max !== null && $length > $this->max) {
{
$message = $this->tooLong !== null ? $this->tooLong : Yii::t('yii', '{attribute} is too long (maximum is {max} characters).'); $message = $this->tooLong !== null ? $this->tooLong : Yii::t('yii', '{attribute} is too long (maximum is {max} characters).');
$this->addError($object, $attribute, $message, array('{max}' => $this->max)); $this->addError($object, $attribute, $message, array('{max}' => $this->max));
} }
if ($this->is !== null && $length !== $this->is) if ($this->is !== null && $length !== $this->is) {
{ $message = $this->notEqual !== null ? $this->notEqual : Yii::t('yii', '{attribute} is of the wrong length (should be {length} characters).');
$message = $this->message !== null ? $this->message : Yii::t('yii', '{attribute} is of the wrong length (should be {length} characters).');
$this->addError($object, $attribute, $message, array('{length}' => $this->is)); $this->addError($object, $attribute, $message, array('{length}' => $this->is));
} }
} }
@ -96,62 +107,63 @@ class CStringValidator extends Validator
* @param \yii\base\Model $object the data object being validated * @param \yii\base\Model $object the data object being validated
* @param string $attribute the name of the attribute to be validated. * @param string $attribute the name of the attribute to be validated.
* @return string the client-side validation script. * @return string the client-side validation script.
* @see CActiveForm::enableClientValidation
* @since 1.1.7
*/ */
public function clientValidateAttribute($object, $attribute) public function clientValidateAttribute($object, $attribute)
{ {
$label = $object->getAttributeLabel($attribute); $label = $object->getAttributeLabel($attribute);
$value = $object->$attribute;
if (($message = $this->message) === null) if (($notEqual = $this->notEqual) === null) {
$message = Yii::t('yii', '{attribute} is of the wrong length (should be {length} characters).'); $notEqual = Yii::t('yii', '{attribute} is of the wrong length (should be {length} characters).');
$message = strtr($message, array( }
$notEqual = strtr($notEqual, array(
'{attribute}' => $label, '{attribute}' => $label,
'{value}' => $value,
'{length}' => $this->is, '{length}' => $this->is,
)); ));
if (($tooShort = $this->tooShort) === null) if (($tooShort = $this->tooShort) === null) {
$tooShort = Yii::t('yii', '{attribute} is too short (minimum is {min} characters).'); $tooShort = Yii::t('yii', '{attribute} is too short (minimum is {min} characters).');
}
$tooShort = strtr($tooShort, array( $tooShort = strtr($tooShort, array(
'{attribute}' => $label, '{attribute}' => $label,
'{value}' => $value,
'{min}' => $this->min, '{min}' => $this->min,
)); ));
if (($tooLong = $this->tooLong) === null) if (($tooLong = $this->tooLong) === null) {
$tooLong = Yii::t('yii', '{attribute} is too long (maximum is {max} characters).'); $tooLong = Yii::t('yii', '{attribute} is too long (maximum is {max} characters).');
}
$tooLong = strtr($tooLong, array( $tooLong = strtr($tooLong, array(
'{attribute}' => $label, '{attribute}' => $label,
'{value}' => $value,
'{max}' => $this->max, '{max}' => $this->max,
)); ));
$js = ''; $js = '';
if ($this->min !== null) if ($this->min !== null) {
{
$js .= " $js .= "
if(value.length< {$this->min}) { if(value.length< {$this->min}) {
messages.push(" . json_encode($tooShort) . "); messages.push(" . json_encode($tooShort) . ");
} }
"; ";
} }
if ($this->max !== null) if ($this->max !== null) {
{
$js .= " $js .= "
if(value.length> {$this->max}) { if(value.length> {$this->max}) {
messages.push(" . json_encode($tooLong) . "); messages.push(" . json_encode($tooLong) . ");
} }
"; ";
} }
if ($this->is !== null) if ($this->is !== null) {
{
$js .= " $js .= "
if(value.length!= {$this->is}) { if(value.length!= {$this->is}) {
messages.push(" . json_encode($message) . "); messages.push(" . json_encode($notEqual) . ");
} }
"; ";
} }
if ($this->allowEmpty) if ($this->allowEmpty) {
{
$js = " $js = "
if($.trim(value)!='') { if($.trim(value)!='') {
$js $js

106
framework/validators/TypeValidator.php

@ -1,106 +0,0 @@
<?php
/**
* CTypeValidator class file.
*
* @link http://www.yiiframework.com/
* @copyright Copyright &copy; 2008-2012 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yii\validators;
/**
* CTypeValidator verifies if the attribute is of the type specified by {@link type}.
*
* The following data types are supported:
* <ul>
* <li><b>integer</b> A 32-bit signed integer data type.</li>
* <li><b>float</b> A double-precision floating point number data type.</li>
* <li><b>string</b> A string data type.</li>
* <li><b>array</b> An array value. </li>
* <li><b>date</b> A date data type.</li>
* <li><b>time</b> A time data type (available since version 1.0.5).</li>
* <li><b>datetime</b> A date and time data type (available since version 1.0.5).</li>
* </ul>
*
* For <b>date</b> type, the property {@link dateFormat}
* will be used to determine how to parse the date string. If the given date
* value doesn't follow the format, the attribute is considered as invalid.
*
* Starting from version 1.1.7, we have a dedicated date validator {@link CDateValidator}.
* Please consider using this validator to validate a date-typed value.
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @version $Id: CTypeValidator.php 3052 2011-03-12 14:27:07Z qiang.xue $
* @package system.validators
* @since 1.0
*/
class CTypeValidator extends Validator
{
/**
* @var string the data type that the attribute should be. Defaults to 'string'.
* Valid values include 'string', 'integer', 'float', 'array', 'date', 'time' and 'datetime'.
* Note that 'time' and 'datetime' have been available since version 1.0.5.
*/
public $type = 'string';
/**
* @var string the format pattern that the date value should follow. Defaults to 'MM/dd/yyyy'.
* Please see {@link CDateTimeParser} for details about how to specify a date format.
* This property is effective only when {@link type} is 'date'.
*/
public $dateFormat = 'MM/dd/yyyy';
/**
* @var string the format pattern that the time value should follow. Defaults to 'hh:mm'.
* Please see {@link CDateTimeParser} for details about how to specify a time format.
* This property is effective only when {@link type} is 'time'.
* @since 1.0.5
*/
public $timeFormat = 'hh:mm';
/**
* @var string the format pattern that the datetime value should follow. Defaults to 'MM/dd/yyyy hh:mm'.
* Please see {@link CDateTimeParser} for details about how to specify a datetime format.
* This property is effective only when {@link type} is 'datetime'.
* @since 1.0.5
*/
public $datetimeFormat = 'MM/dd/yyyy hh:mm';
/**
* @var boolean whether the attribute value can be null or empty. Defaults to true,
* meaning that if the attribute is empty, it is considered valid.
*/
public $allowEmpty = true;
/**
* Validates the attribute of the object.
* If there is any error, the error message is added to the object.
* @param \yii\base\Model $object the object being validated
* @param string $attribute the attribute being validated
*/
public function validateAttribute($object, $attribute)
{
$value = $object->$attribute;
if ($this->allowEmpty && $this->isEmpty($value))
return;
if ($this->type === 'integer')
$valid = preg_match('/^[-+]?[0-9]+$/', trim($value));
elseif ($this->type === 'float')
$valid = preg_match('/^[-+]?([0-9]*\.)?[0-9]+([eE][-+]?[0-9]+)?$/', trim($value));
elseif ($this->type === 'date')
$valid = CDateTimeParser::parse($value, $this->dateFormat, array('month' => 1, 'day' => 1, 'hour' => 0, 'minute' => 0, 'second' => 0)) !== false;
elseif ($this->type === 'time')
$valid = CDateTimeParser::parse($value, $this->timeFormat) !== false;
elseif ($this->type === 'datetime')
$valid = CDateTimeParser::parse($value, $this->datetimeFormat, array('month' => 1, 'day' => 1, 'hour' => 0, 'minute' => 0, 'second' => 0)) !== false;
elseif ($this->type === 'array')
$valid = is_array($value);
else
return;
if (!$valid)
{
$message = $this->message !== null ? $this->message : Yii::t('yii', '{attribute} must be {type}.');
$this->addError($object, $attribute, $message, array('{type}' => $this->type));
}
}
}

1
framework/validators/UrlValidator.php

@ -102,6 +102,7 @@ class UrlValidator extends Validator
$message = $this->message !== null ? $this->message : Yii::t('yii', '{attribute} is not a valid URL.'); $message = $this->message !== null ? $this->message : Yii::t('yii', '{attribute} is not a valid URL.');
$message = strtr($message, array( $message = strtr($message, array(
'{attribute}' => $object->getAttributeLabel($attribute), '{attribute}' => $object->getAttributeLabel($attribute),
'{value}' => $object->$attribute,
)); ));
if (strpos($this->pattern, '{schemes}') !== false) if (strpos($this->pattern, '{schemes}') !== false)

25
framework/validators/Validator.php

@ -60,22 +60,21 @@ abstract class Validator extends \yii\base\Component
'url' => '\yii\validators\UrlValidator', 'url' => '\yii\validators\UrlValidator',
'safe' => '\yii\validators\SafeValidator', 'safe' => '\yii\validators\SafeValidator',
'unsafe' => '\yii\validators\UnsafeValidator', 'unsafe' => '\yii\validators\UnsafeValidator',
'numerical' => '\yii\validators\NumberValidator',
'boolean' => '\yii\validators\BooleanValidator',
'integer' => '\yii\validators\IntegerValidator',
'float' => '\yii\validators\FloatValidator',
'string' => '\yii\validators\StringValidator',
'date' => '\yii\validators\DateValidator',
'file' => '\yii\validators\FileValidator',
'filter' => '\yii\validators\FilterValidator', 'filter' => '\yii\validators\FilterValidator',
'compare' => '\yii\validators\CompareValidator',
'length' => '\yii\validators\StringValidator',
'in' => '\yii\validators\RangeValidator',
'captcha' => '\yii\validators\CaptchaValidator', 'captcha' => '\yii\validators\CaptchaValidator',
'type' => '\yii\validators\TypeValidator',
'default' => '\yii\validators\DefaultValueValidator', 'default' => '\yii\validators\DefaultValueValidator',
'in' => '\yii\validators\RangeValidator',
'boolean' => '\yii\validators\BooleanValidator',
'string' => '\yii\validators\StringValidator',
'integer' => array(
'class' => '\yii\validators\NumberValidator',
'integerOnly' => true,
),
'double' => '\yii\validators\NumberValidator',
'compare' => '\yii\validators\CompareValidator',
'file' => '\yii\validators\FileValidator',
'date' => '\yii\validators\DateValidator',
'unique' => '\yii\validators\UniqueValidator', 'unique' => '\yii\validators\UniqueValidator',
'exist' => '\yii\validators\ExistValidator', 'exist' => '\yii\validators\ExistValidator',

2
todo.txt

@ -0,0 +1,2 @@
- CompareValidator::clientValidateAttribute(): search for "CHtml::activeId"
- FileValidator, UniqueValidator, ExistValidator, DateValidator: TBD
Loading…
Cancel
Save