Yii2 framework backup
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

94 lines
2.8 KiB

13 years ago
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
13 years ago
* @license http://www.yiiframework.com/license/
*/
13 years ago
namespace yii\validators;
use Yii;
13 years ago
/**
13 years ago
* 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.
13 years ago
*
* @author Qiang Xue <qiang.xue@gmail.com>
13 years ago
* @since 2.0
13 years ago
*/
13 years ago
class BooleanValidator extends Validator
13 years ago
{
/**
* @var mixed the value representing true status. Defaults to '1'.
*/
public $trueValue = '1';
/**
* @var mixed the value representing false status. Defaults to '0'.
*/
public $falseValue = '0';
/**
* @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 [[trueValue]] or [[falseValue]].
* Defaults to false, meaning only the value needs to be matched.
*/
public $strict = false;
13 years ago
/**
* @inheritdoc
*/
public function init()
{
parent::init();
if ($this->message === null) {
$this->message = Yii::t('yii', '{attribute} must be either "{true}" or "{false}".');
}
}
/**
* @inheritdoc
*/
protected function validateValue($value)
{
$valid = !$this->strict && ($value == $this->trueValue || $value == $this->falseValue)
|| $this->strict && ($value === $this->trueValue || $value === $this->falseValue);
if (!$valid) {
return [$this->message, [
9 years ago
'true' => $this->trueValue === true ? 'true' : $this->trueValue,
'false' => $this->falseValue === false ? 'false' : $this->falseValue,
]];
}
return null;
}
13 years ago
/**
* @inheritdoc
*/
public function clientValidateAttribute($model, $attribute, $view)
{
$options = [
'trueValue' => $this->trueValue,
'falseValue' => $this->falseValue,
'message' => Yii::$app->getI18n()->format($this->message, [
'attribute' => $model->getAttributeLabel($attribute),
9 years ago
'true' => $this->trueValue === true ? 'true' : $this->trueValue,
'false' => $this->falseValue === false ? 'false' : $this->falseValue,
], Yii::$app->language),
];
if ($this->skipOnEmpty) {
$options['skipOnEmpty'] = 1;
}
if ($this->strict) {
$options['strict'] = 1;
}
12 years ago
ValidationAsset::register($view);
return 'yii.validation.boolean(value, messages, ' . json_encode($options, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) . ');';
}
13 years ago
}