-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathCurpValidator.php
executable file
·73 lines (67 loc) · 2.11 KB
/
CurpValidator.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
<?php
/**
* @author Carlos Ramos <[email protected]>
* @copyright 2015 Carlos Ramos.
* @license http://www.opensource.org/licenses/mit-license.php MIT License
* @version 0.0.1
* @link https://github.com/ktaris/yii2-mexvalidators
*/
namespace jcabanillas\mexvalidators;
use yii\validators\Validator;
/**
* Valida que la cadena sea una CURP válida según las leyes mexicanas.
*
* Validates that the string is a valid CURP according to Mexican law.
*/
class CurpValidator extends Validator
{
/**
* Determina si se convierte el campo a mayúsculas automáticamente.
* @var boolean determines if the field is automatically converted to uppercase.
*/
public $toUpper = true;
/**
* @inheritdoc
*/
public function init()
{
if ($this->message === null) {
$this->message = \Yii::t('yii', '{attribute} must be a string.');
}
}
/**
* @inheritdoc
*/
public function validateAttribute($model, $attribute)
{
//Uppercase the value (all RFC must be uppercase).
if ($this->toUpper === true) {
$model->{$attribute} = strtoupper($model->{$attribute});
}
//Proceed with value validation.
$value = $model->{$attribute};
$errorMessage = $this->validateValue($value);
if ($errorMessage) {
$this->addError($model, $attribute, $this->message);
}
}
/**
* @inheritdoc
*/
protected function validateValue($value)
{
//Check the attribute is a string.
if (!is_string($value)) {
return $this->message;
}
//Check against the pattern.
$pattern = '/^[A-Z][A,E,I,O,U,X][A-Z]{2}[0-9]{2}[0-1][0-9][0-3][0-9][M,H][A-Z]{2}[B,C,D,F,G,H,J,K,L,M,N,Ñ,P,Q,R,S,T,V,W,X,Y,Z]{3}[0-9,A-Z][0-9]$/';
$result = preg_match($pattern, $value);
if ($result !== 1) { //there was no match.
$this->message = \Yii::t('yii', 'The format of {attribute} is invalid.');
return $this->message;
}
//Return false (meaning no error occurred).
return false;
}
}