You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

86 satır
2.3KB

  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\web\JsExpression;
  12. use yii\helpers\Json;
  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 boolean 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. $pattern = Html::escapeJsRegularExpression($this->pattern);
  61. $options = [
  62. 'pattern' => new JsExpression($pattern),
  63. 'not' => $this->not,
  64. 'message' => Yii::$app->getI18n()->format($this->message, [
  65. 'attribute' => $model->getAttributeLabel($attribute),
  66. ], Yii::$app->language),
  67. ];
  68. if ($this->skipOnEmpty) {
  69. $options['skipOnEmpty'] = 1;
  70. }
  71. ValidationAsset::register($view);
  72. return 'yii.validation.regularExpression(value, messages, ' . Json::htmlEncode($options) . ');';
  73. }
  74. }