forked from phalcon/cphalcon
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Regex.zep
97 lines (85 loc) · 2.36 KB
/
Regex.zep
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
/**
* This file is part of the Phalcon Framework.
*
* (c) Phalcon Team <team@phalconphp.com>
*
* For the full copyright and license information, please view the LICENSE.txt
* file that was distributed with this source code.
*/
namespace Phalcon\Validation\Validator;
use Phalcon\Messages\Message;
use Phalcon\Validation;
use Phalcon\Validation\Validator;
/**
* Phalcon\Validation\Validator\Regex
*
* Allows validate if the value of a field matches a regular expression
*
* <code>
* use Phalcon\Validation;
* use Phalcon\Validation\Validator\Regex as RegexValidator;
*
* $validator = new Validation();
*
* $validator->add(
* "created_at",
* new RegexValidator(
* [
* "pattern" => "/^[0-9]{4}[-\/](0[1-9]|1[12])[-\/](0[1-9]|[12][0-9]|3[01])$/",
* "message" => "The creation date is invalid",
* ]
* )
* );
*
* $validator->add(
* [
* "created_at",
* "name",
* ],
* new RegexValidator(
* [
* "pattern" => [
* "created_at" => "/^[0-9]{4}[-\/](0[1-9]|1[12])[-\/](0[1-9]|[12][0-9]|3[01])$/",
* "name" => "/^[a-z]$/",
* ],
* "message" => [
* "created_at" => "The creation date is invalid",
* "name" => "The name is invalid",
* ]
* ]
* )
* );
* </code>
*/
class Regex extends Validator
{
protected template = "Field :field does not match the required format";
/**
* Executes the validation
*/
public function validate(<Validation> validation, var field) -> bool
{
var matches, value, pattern;
bool failed;
// Regular expression is set in the option 'pattern'
// Check if the value match using preg_match in the PHP userland
let matches = null;
let value = validation->getValue(field);
let pattern = this->getOption("pattern");
if typeof pattern == "array" {
let pattern = pattern[field];
}
if preg_match(pattern, value, matches) {
let failed = matches[0] != value;
} else {
let failed = true;
}
if failed {
validation->appendMessage(
this->messageFactory(validation, field)
);
return false;
}
return true;
}
}