RegularExpressionValidator.php 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. <?php
  2. /**
  3. * @link http://www.yiiframework.com/
  4. * @copyright Copyright (c) 2008 Yii Software LLC
  5. * @license http://www.yiiframework.com/license/
  6. */
  7. namespace yii\validators;
  8. use Yii;
  9. use yii\base\InvalidConfigException;
  10. use yii\helpers\Html;
  11. use yii\helpers\Json;
  12. use yii\web\JsExpression;
  13. /**
  14. * RegularExpressionValidator validates that the attribute value matches the specified [[pattern]].
  15. *
  16. * If the [[not]] property is set true, the validator will ensure the attribute value do NOT match the [[pattern]].
  17. *
  18. * @author Qiang Xue <qiang.xue@gmail.com>
  19. * @since 2.0
  20. */
  21. class RegularExpressionValidator extends Validator
  22. {
  23. /**
  24. * @var string the regular expression to be matched with
  25. */
  26. public $pattern;
  27. /**
  28. * @var bool whether to invert the validation logic. Defaults to false. If set to true,
  29. * the regular expression defined via [[pattern]] should NOT match the attribute value.
  30. */
  31. public $not = false;
  32. /**
  33. * {@inheritdoc}
  34. */
  35. public function init()
  36. {
  37. parent::init();
  38. if ($this->pattern === null) {
  39. throw new InvalidConfigException('The "pattern" property must be set.');
  40. }
  41. if ($this->message === null) {
  42. $this->message = Yii::t('yii', '{attribute} is invalid.');
  43. }
  44. }
  45. /**
  46. * {@inheritdoc}
  47. */
  48. protected function validateValue($value)
  49. {
  50. $valid = !is_array($value) &&
  51. (!$this->not && preg_match($this->pattern, $value)
  52. || $this->not && !preg_match($this->pattern, $value));
  53. return $valid ? null : [$this->message, []];
  54. }
  55. /**
  56. * {@inheritdoc}
  57. */
  58. public function clientValidateAttribute($model, $attribute, $view)
  59. {
  60. ValidationAsset::register($view);
  61. $options = $this->getClientOptions($model, $attribute);
  62. return 'yii.validation.regularExpression(value, messages, ' . Json::htmlEncode($options) . ');';
  63. }
  64. /**
  65. * {@inheritdoc}
  66. */
  67. public function getClientOptions($model, $attribute)
  68. {
  69. $pattern = Html::escapeJsRegularExpression($this->pattern);
  70. $options = [
  71. 'pattern' => new JsExpression($pattern),
  72. 'not' => $this->not,
  73. 'message' => $this->formatMessage($this->message, [
  74. 'attribute' => $model->getAttributeLabel($attribute),
  75. ]),
  76. ];
  77. if ($this->skipOnEmpty) {
  78. $options['skipOnEmpty'] = 1;
  79. }
  80. return $options;
  81. }
  82. }