1: <?php
2: /**
3: * Wei Framework
4: *
5: * @copyright Copyright (c) 2008-2015 Twin Huang
6: * @license http://opensource.org/licenses/mit-license.php MIT License
7: */
8:
9: namespace Wei\Validator;
10:
11: /**
12: * Check if the input is valid by specified regular expression
13: *
14: * @author Twin Huang <twinhuang@qq.com>
15: */
16: class Regex extends BaseValidator
17: {
18: protected $patternMessage = '%name% must match against pattern "%pattern%"';
19:
20: protected $negativeMessage = '%name% must not match against pattern "%pattern%"';
21:
22: /**
23: * The regex pattern
24: *
25: * @var string
26: */
27: protected $pattern;
28:
29: /**
30: * Returns whether the $input value is valid
31: *
32: * @param mixed $input
33: * @param null|string $pattern
34: * @return bool
35: */
36: public function __invoke($input, $pattern = null)
37: {
38: is_string($pattern) && $this->storeOption('pattern', $pattern);
39:
40: return $this->isValid($input);
41: }
42:
43: /**
44: * {@inheritdoc}
45: */
46: protected function doValidate($input)
47: {
48: if (!$this->isString($input)) {
49: $this->addError('notString');
50: return false;
51: }
52:
53: if (!preg_match($this->pattern, $input)) {
54: $this->addError('pattern');
55: return false;
56: }
57:
58: return true;
59: }
60: }
61: