|
1
|
|
|
<?php |
|
2
|
|
|
/** |
|
3
|
|
|
* Created by PhpStorm. |
|
4
|
|
|
* User: floor12 |
|
5
|
|
|
* Date: 19.01.2017 |
|
6
|
|
|
* Time: 18:18 |
|
7
|
|
|
*/ |
|
8
|
|
|
|
|
9
|
|
|
namespace floor12\phone; |
|
10
|
|
|
|
|
11
|
|
|
use Yii; |
|
12
|
|
|
use yii\base\Model; |
|
13
|
|
|
use yii\base\NotSupportedException; |
|
14
|
|
|
use yii\validators\Validator; |
|
15
|
|
|
use yii\web\View; |
|
16
|
|
|
|
|
17
|
|
|
class PhoneValidator extends Validator |
|
18
|
|
|
{ |
|
19
|
|
|
|
|
20
|
|
|
/** |
|
21
|
|
|
* @param Model $model |
|
22
|
|
|
* @param string $attribute |
|
23
|
|
|
* @throws NotSupportedException |
|
24
|
|
|
*/ |
|
25
|
|
|
public function validateAttribute($model, $attribute) |
|
26
|
|
|
{ |
|
27
|
|
|
$model->$attribute = $this->clear($model->$attribute); |
|
28
|
|
|
$result = $this->validateValue($model->$attribute); |
|
29
|
|
|
if (!empty($result)) { |
|
30
|
|
|
$this->addError($model, $attribute, $result[0], $result[1]); |
|
31
|
|
|
} |
|
32
|
|
|
} |
|
33
|
|
|
|
|
34
|
|
|
/** |
|
35
|
|
|
* @param $value |
|
36
|
|
|
* @return mixed |
|
37
|
|
|
*/ |
|
38
|
|
|
protected function clear($value) |
|
39
|
|
|
{ |
|
40
|
|
|
return str_replace([' ', '-', '(', ')', '_', '+'], '', trim($value)); |
|
41
|
|
|
} |
|
42
|
|
|
|
|
43
|
|
|
/** |
|
44
|
|
|
* @return array |
|
45
|
|
|
*/ |
|
46
|
|
|
protected function validateValue($value) |
|
47
|
|
|
{ |
|
48
|
|
|
if (is_array($value) || is_object($value)) |
|
49
|
|
|
return [Yii::t('yii', '{attribute} is invalid.'), []]; |
|
50
|
|
|
|
|
51
|
|
|
if (!is_numeric($value)) |
|
52
|
|
|
return ["Телефонный номер должен содержать только цифры.", []]; |
|
53
|
|
|
|
|
54
|
|
|
if ((strlen(strval($value)) > 12) || (strlen(strval($value)) < 11)) |
|
55
|
|
|
return ["Телефонный номер должны быть длиною 11 или 12 цифр.", []]; |
|
56
|
|
|
} |
|
57
|
|
|
|
|
58
|
|
|
/** |
|
59
|
|
|
* @param mixed $value |
|
60
|
|
|
* @param null $error |
|
|
|
|
|
|
61
|
|
|
* @return bool |
|
62
|
|
|
* @throws NotSupportedException |
|
63
|
|
|
*/ |
|
64
|
|
|
public function validate($value, &$error = null) |
|
65
|
|
|
{ |
|
66
|
|
|
$value = $this->clear($value); |
|
67
|
|
|
$result = $this->validateValue($this->clear($value)); |
|
68
|
|
|
if (!empty($result)) { |
|
69
|
|
|
$error = $result[0]; |
|
70
|
|
|
return false; |
|
71
|
|
|
} |
|
72
|
|
|
return true; |
|
73
|
|
|
} |
|
74
|
|
|
|
|
75
|
|
|
/** |
|
76
|
|
|
* @param Model $model |
|
77
|
|
|
* @param string $attribute |
|
78
|
|
|
* @param View $view |
|
79
|
|
|
* @return string|null |
|
80
|
|
|
*/ |
|
81
|
|
|
public function clientValidateAttribute($model, $attribute, $view) |
|
82
|
|
|
{ |
|
83
|
|
|
PhoneValidatorAsset::register($view); |
|
84
|
|
|
$options = $this->getClientOptions($model, $attribute); |
|
85
|
|
|
return 'validatePhone(value, messages, ' . json_encode($options, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) . ');'; |
|
86
|
|
|
} |
|
87
|
|
|
|
|
88
|
|
|
} |