1
|
|
|
<?php |
2
|
|
|
namespace Yiisoft\Validator\Rule; |
3
|
|
|
|
4
|
|
|
use Yiisoft\Validator\DataSetInterface; |
5
|
|
|
use Yiisoft\Validator\Result; |
6
|
|
|
use Yiisoft\Validator\Rule; |
7
|
|
|
|
8
|
|
|
/** |
9
|
|
|
* RequiredValidator validates that the specified attribute does not have null or empty value. |
10
|
|
|
*/ |
11
|
|
|
class Required extends Rule |
12
|
|
|
{ |
13
|
|
|
/** |
14
|
|
|
* @var bool whether the comparison between the attribute value and [[requiredValue]] is strict. |
15
|
|
|
* When this is true, both the values and types must match. |
16
|
|
|
* Defaults to false, meaning only the values need to match. |
17
|
|
|
* Note that when [[requiredValue]] is null, if this property is true, the validator will check |
18
|
|
|
* if the attribute value is null; If this property is false, the validator will call [[isEmpty]] |
19
|
|
|
* to check if the attribute value is empty. |
20
|
|
|
*/ |
21
|
|
|
private bool $strict = false; |
22
|
|
|
/** |
23
|
|
|
* @var string the user-defined error message. It may contain the following placeholders which |
24
|
|
|
* will be replaced accordingly by the validator: |
25
|
|
|
* |
26
|
|
|
* - `{attribute}`: the label of the attribute being validated |
27
|
|
|
* - `{value}`: the value of the attribute being validated |
28
|
|
|
* - `{requiredValue}`: the value of [[requiredValue]] |
29
|
|
|
*/ |
30
|
|
|
private string $message = 'Value cannot be blank.'; |
31
|
|
|
|
32
|
3 |
|
protected function validateValue($value, DataSetInterface $dataSet = null): Result |
33
|
|
|
{ |
34
|
3 |
|
$result = new Result(); |
35
|
|
|
|
36
|
3 |
|
if (($this->strict && $value !== null) || (!$this->strict && !$this->isEmpty(is_string($value) ? trim($value) : $value))) { |
37
|
3 |
|
return $result; |
38
|
|
|
} |
39
|
|
|
|
40
|
1 |
|
$result->addError($this->formatMessage($this->message)); |
41
|
1 |
|
return $result; |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
public function message(string $message): self |
45
|
|
|
{ |
46
|
|
|
$this->message = $message; |
47
|
|
|
return $this; |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
public function strict(): self |
51
|
|
|
{ |
52
|
|
|
$this->strict = true; |
53
|
|
|
return $this; |
54
|
|
|
} |
55
|
|
|
} |
56
|
|
|
|