123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122 |
- <?php
- namespace yii\validators;
- use Yii;
- class RequiredValidator extends Validator
- {
-
- public $skipOnEmpty = false;
-
- public $requiredValue;
-
- public $strict = false;
-
- public $message;
-
- public function init()
- {
- parent::init();
- if ($this->message === null) {
- $this->message = $this->requiredValue === null ? Yii::t('yii', '{attribute} cannot be blank.')
- : Yii::t('yii', '{attribute} must be "{requiredValue}".');
- }
- }
-
- protected function validateValue($value)
- {
- if ($this->requiredValue === null) {
- if ($this->strict && $value !== null || !$this->strict && !$this->isEmpty(is_string($value) ? trim($value) : $value)) {
- return null;
- }
- } elseif (!$this->strict && $value == $this->requiredValue || $this->strict && $value === $this->requiredValue) {
- return null;
- }
- if ($this->requiredValue === null) {
- return [$this->message, []];
- }
- return [$this->message, [
- 'requiredValue' => $this->requiredValue,
- ]];
- }
-
- public function clientValidateAttribute($model, $attribute, $view)
- {
- ValidationAsset::register($view);
- $options = $this->getClientOptions($model, $attribute);
- return 'yii.validation.required(value, messages, ' . json_encode($options, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) . ');';
- }
-
- public function getClientOptions($model, $attribute)
- {
- $options = [];
- if ($this->requiredValue !== null) {
- $options['message'] = $this->formatMessage($this->message, [
- 'requiredValue' => $this->requiredValue,
- ]);
- $options['requiredValue'] = $this->requiredValue;
- } else {
- $options['message'] = $this->message;
- }
- if ($this->strict) {
- $options['strict'] = 1;
- }
- $options['message'] = $this->formatMessage($options['message'], [
- 'attribute' => $model->getAttributeLabel($attribute),
- ]);
- return $options;
- }
- }
|