4 * This file is part of the Symfony package.
6 * (c) Fabien Potencier <fabien@symfony.com>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Symfony\Component\Validator\Constraints;
14 use Symfony\Component\Validator\Constraint;
18 * @Target({"PROPERTY", "METHOD", "ANNOTATION"})
20 * @author Bernhard Schussek <bschussek@gmail.com>
22 class Regex extends Constraint
24 const REGEX_FAILED_ERROR = 'de1e3db3-5ed4-4941-aae4-59f3667cc3a3';
26 protected static $errorNames = array(
27 self::REGEX_FAILED_ERROR => 'REGEX_FAILED_ERROR',
30 public $message = 'This value is not valid.';
38 public function getDefaultOption()
46 public function getRequiredOptions()
48 return array('pattern');
52 * Converts the htmlPattern to a suitable format for HTML5 pattern.
53 * Example: /^[a-z]+$/ would be converted to [a-z]+
54 * However, if options are specified, it cannot be converted.
56 * Pattern is also ignored if match=false since the pattern should
57 * then be reversed before application.
59 * @see http://dev.w3.org/html5/spec/single-page.html#the-pattern-attribute
63 public function getHtmlPattern()
65 // If htmlPattern is specified, use it
66 if (null !== $this->htmlPattern) {
67 return empty($this->htmlPattern)
72 // Quit if delimiters not at very beginning/end (e.g. when options are passed)
73 if ($this->pattern[0] !== $this->pattern[strlen($this->pattern) - 1]) {
77 $delimiter = $this->pattern[0];
79 // Unescape the delimiter
80 $pattern = str_replace('\\'.$delimiter, $delimiter, substr($this->pattern, 1, -1));
82 // If the pattern is inverted, we can simply wrap it in
85 return '((?!'.$pattern.').)*';
88 // If the pattern contains an or statement, wrap the pattern in
89 // .*(pattern).* and quit. Otherwise we'd need to parse the pattern
90 if (false !== strpos($pattern, '|')) {
91 return '.*('.$pattern.').*';
94 // Trim leading ^, otherwise prepend .*
95 $pattern = '^' === $pattern[0] ? substr($pattern, 1) : '.*'.$pattern;
97 // Trim trailing $, otherwise append .*
98 $pattern = '$' === $pattern[strlen($pattern) - 1] ? substr($pattern, 0, -1) : $pattern.'.*';