123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106 |
- <?php
- namespace yii\validators;
- use Yii;
- class BooleanValidator extends Validator
- {
-
- public $trueValue = '1';
-
- public $falseValue = '0';
-
- public $strict = false;
-
- public function init()
- {
- parent::init();
- if ($this->message === null) {
- $this->message = Yii::t('yii', '{attribute} must be either "{true}" or "{false}".');
- }
- }
-
- protected function validateValue($value)
- {
- if ($this->strict) {
- $valid = $value === $this->trueValue || $value === $this->falseValue;
- } else {
- $valid = $value == $this->trueValue || $value == $this->falseValue;
- }
- if (!$valid) {
- return [$this->message, [
- 'true' => $this->trueValue === true ? 'true' : $this->trueValue,
- 'false' => $this->falseValue === false ? 'false' : $this->falseValue,
- ]];
- }
- return null;
- }
-
- public function clientValidateAttribute($model, $attribute, $view)
- {
- ValidationAsset::register($view);
- $options = $this->getClientOptions($model, $attribute);
- return 'yii.validation.boolean(value, messages, ' . json_encode($options, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) . ');';
- }
-
- public function getClientOptions($model, $attribute)
- {
- $options = [
- 'trueValue' => $this->trueValue,
- 'falseValue' => $this->falseValue,
- 'message' => $this->formatMessage($this->message, [
- 'attribute' => $model->getAttributeLabel($attribute),
- 'true' => $this->trueValue === true ? 'true' : $this->trueValue,
- 'false' => $this->falseValue === false ? 'false' : $this->falseValue,
- ]),
- ];
- if ($this->skipOnEmpty) {
- $options['skipOnEmpty'] = 1;
- }
- if ($this->strict) {
- $options['strict'] = 1;
- }
- return $options;
- }
- }
|