|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace luya\validators; |
|
4
|
|
|
|
|
5
|
|
|
use yii\validators\Validator; |
|
6
|
|
|
|
|
7
|
|
|
/** |
|
8
|
|
|
* Checks a given string for given strength attributes. |
|
9
|
|
|
* |
|
10
|
|
|
* This validator is commonly used to validate the strength of passwords. |
|
11
|
|
|
* |
|
12
|
|
|
* @author Basil Suter <[email protected]> |
|
13
|
|
|
* @since 1.0.6 |
|
14
|
|
|
*/ |
|
15
|
|
|
class StrengthValidator extends Validator |
|
16
|
|
|
{ |
|
17
|
|
|
/** |
|
18
|
|
|
* @var integer The minimum length of the string. |
|
19
|
|
|
*/ |
|
20
|
|
|
public $length = 8; |
|
21
|
|
|
|
|
22
|
|
|
/** |
|
23
|
|
|
* @var boolean Whether special chars are required in the string or not. |
|
24
|
|
|
*/ |
|
25
|
|
|
public $specials = true; |
|
26
|
|
|
|
|
27
|
|
|
/** |
|
28
|
|
|
* @var boolean Whether numbers are required in the string or not. |
|
29
|
|
|
*/ |
|
30
|
|
|
public $numbers = true; |
|
31
|
|
|
|
|
32
|
|
|
/** |
|
33
|
|
|
* @var boolean Whether letters are required in the string or not. |
|
34
|
|
|
*/ |
|
35
|
|
|
public $letters = true; |
|
36
|
|
|
|
|
37
|
|
|
/** |
|
38
|
|
|
* @var boolean Whether at least one upper char must exist in the string or not. |
|
39
|
|
|
*/ |
|
40
|
|
|
public $uppercase = true; |
|
41
|
|
|
|
|
42
|
|
|
/** |
|
43
|
|
|
* @var boolean Whether at least one lower case char must exist in the string or not. |
|
44
|
|
|
*/ |
|
45
|
|
|
public $lowercase; |
|
46
|
|
|
|
|
47
|
|
|
/** |
|
48
|
|
|
* @inheritdoc |
|
49
|
|
|
*/ |
|
50
|
|
|
public function validateAttribute($model, $attribute) |
|
51
|
|
|
{ |
|
52
|
|
|
$value = $model->{$attribute}; |
|
53
|
|
|
|
|
54
|
|
|
if ($this->length && strlen($value) <= $this->length) { |
|
55
|
|
|
return $model->addError($attribute, 'The string must have at least {$this->length} chars.'); |
|
56
|
|
|
} |
|
57
|
|
|
|
|
58
|
|
|
if ($this->specials && !preg_match('/\W/', $value)) { |
|
59
|
|
|
return $model->addError($attribute, 'The string must contain any special char.'); |
|
60
|
|
|
} |
|
61
|
|
|
|
|
62
|
|
|
if ($this->numbers && !preg_match('/\d/', $value)) { |
|
63
|
|
|
return $model->addError($attribute, 'The string must contain at least one digit'); |
|
64
|
|
|
} |
|
65
|
|
|
|
|
66
|
|
|
if ($this->letters && !preg_match('/\p{L}/', $value)) { |
|
67
|
|
|
return $model->addError($attribute, 'The string must at least have one letter sign.'); |
|
68
|
|
|
} |
|
69
|
|
|
|
|
70
|
|
|
if ($this->uppercase && !preg_match('/[A-Z]/', $value)) { |
|
71
|
|
|
return $model->addError($attribute, 'The string must at least have one upper case letter.'); |
|
72
|
|
|
} |
|
73
|
|
|
|
|
74
|
|
|
if ($this->lowercase && !preg_match('/[a-z]/', $value)) { |
|
75
|
|
|
return $model->addError($attribute, 'The string must at least have one lower case letter.'); |
|
76
|
|
|
} |
|
77
|
|
|
} |
|
78
|
|
|
} |