NumberValidator.php 4.85 KB
Newer Older
w  
Qiang Xue committed
1 2 3
<?php
/**
 * @link http://www.yiiframework.com/
Qiang Xue committed
4
 * @copyright Copyright (c) 2008 Yii Software LLC
w  
Qiang Xue committed
5 6 7
 * @license http://www.yiiframework.com/license/
 */

w  
Qiang Xue committed
8 9
namespace yii\validators;

Qiang Xue committed
10
use Yii;
11
use yii\helpers\Html;
Qiang Xue committed
12
use yii\web\JsExpression;
13
use yii\helpers\Json;
Qiang Xue committed
14

w  
Qiang Xue committed
15
/**
w  
Qiang Xue committed
16
 * NumberValidator validates that the attribute value is a number.
w  
Qiang Xue committed
17
 *
w  
Qiang Xue committed
18 19 20 21
 * The format of the number must match the regular expression specified in [[pattern]].
 * Optionally, you may configure the [[max]] and [[min]] properties to ensure the number
 * is within certain range.
 *
w  
Qiang Xue committed
22
 * @author Qiang Xue <qiang.xue@gmail.com>
w  
Qiang Xue committed
23
 * @since 2.0
w  
Qiang Xue committed
24
 */
w  
Qiang Xue committed
25
class NumberValidator extends Validator
w  
Qiang Xue committed
26
{
Qiang Xue committed
27 28 29 30
	/**
	 * @var boolean whether the attribute value can only be an integer. Defaults to false.
	 */
	public $integerOnly = false;
w  
Qiang Xue committed
31 32 33 34 35 36 37 38 39
	/**
	 * @var integer|float upper limit of the number. Defaults to null, meaning no upper limit.
	 */
	public $max;
	/**
	 * @var integer|float lower limit of the number. Defaults to null, meaning no lower limit.
	 */
	public $min;
	/**
w  
Qiang Xue committed
40
	 * @var string user-defined error message used when the value is bigger than [[max]].
w  
Qiang Xue committed
41 42 43
	 */
	public $tooBig;
	/**
w  
Qiang Xue committed
44
	 * @var string user-defined error message used when the value is smaller than [[min]].
w  
Qiang Xue committed
45 46
	 */
	public $tooSmall;
Qiang Xue committed
47 48 49 50
	/**
	 * @var string the regular expression for matching integers.
	 */
	public $integerPattern = '/^\s*[+-]?\d+\s*$/';
w  
Qiang Xue committed
51
	/**
w  
Qiang Xue committed
52 53
	 * @var string the regular expression for matching numbers. It defaults to a pattern
	 * that matches floating numbers with optional exponential part (e.g. -1.23e-10).
w  
Qiang Xue committed
54
	 */
Qiang Xue committed
55
	public $numberPattern = '/^\s*[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?\s*$/';
w  
Qiang Xue committed
56 57


Qiang Xue committed
58 59 60 61 62 63 64
	/**
	 * Initializes the validator.
	 */
	public function init()
	{
		parent::init();
		if ($this->message === null) {
65 66
			$this->message = $this->integerOnly ? Yii::t('yii', '{attribute} must be an integer.')
				: Yii::t('yii', '{attribute} must be a number.');
Qiang Xue committed
67 68
		}
		if ($this->min !== null && $this->tooSmall === null) {
69
			$this->tooSmall = Yii::t('yii', '{attribute} must be no less than {min}.');
Qiang Xue committed
70 71
		}
		if ($this->max !== null && $this->tooBig === null) {
72
			$this->tooBig = Yii::t('yii', '{attribute} must be no greater than {max}.');
Qiang Xue committed
73 74 75
		}
	}

w  
Qiang Xue committed
76 77 78
	/**
	 * Validates the attribute of the object.
	 * If there is any error, the error message is added to the object.
w  
Qiang Xue committed
79
	 * @param \yii\base\Model $object the object being validated
w  
Qiang Xue committed
80 81
	 * @param string $attribute the attribute being validated
	 */
w  
Qiang Xue committed
82
	public function validateAttribute($object, $attribute)
w  
Qiang Xue committed
83 84
	{
		$value = $object->$attribute;
85
		if (is_array($value)) {
86
			$this->addError($object, $attribute, Yii::t('yii', '{attribute} is invalid.'));
87 88
			return;
		}
Qiang Xue committed
89 90 91
		$pattern = $this->integerOnly ? $this->integerPattern : $this->numberPattern;
		if (!preg_match($pattern, "$value")) {
			$this->addError($object, $attribute, $this->message);
w  
Qiang Xue committed
92
		}
w  
Qiang Xue committed
93
		if ($this->min !== null && $value < $this->min) {
Qiang Xue committed
94
			$this->addError($object, $attribute, $this->tooSmall, array('{min}' => $this->min));
w  
Qiang Xue committed
95
		}
w  
Qiang Xue committed
96
		if ($this->max !== null && $value > $this->max) {
Qiang Xue committed
97
			$this->addError($object, $attribute, $this->tooBig, array('{max}' => $this->max));
w  
Qiang Xue committed
98 99 100
		}
	}

Qiang Xue committed
101 102 103 104 105 106 107 108 109 110 111 112
	/**
	 * Validates the given value.
	 * @param mixed $value the value to be validated.
	 * @return boolean whether the value is valid.
	 */
	public function validateValue($value)
	{
		return preg_match($this->integerOnly ? $this->integerPattern : $this->numberPattern, "$value")
			&& ($this->min === null || $value >= $this->min)
			&& ($this->max === null || $value <= $this->max);
	}

w  
Qiang Xue committed
113 114
	/**
	 * Returns the JavaScript needed for performing client-side validation.
w  
Qiang Xue committed
115
	 * @param \yii\base\Model $object the data object being validated
w  
Qiang Xue committed
116
	 * @param string $attribute the name of the attribute to be validated.
117 118
	 * @param \yii\base\View $view the view object that is going to be used to render views or view files
	 * containing a model form with this validator applied.
w  
Qiang Xue committed
119 120
	 * @return string the client-side validation script.
	 */
121
	public function clientValidateAttribute($object, $attribute, $view)
w  
Qiang Xue committed
122 123
	{
		$label = $object->getAttributeLabel($attribute);
124 125 126 127 128 129 130 131 132
		$value = $object->$attribute;

		$options = array(
			'pattern' => new JsExpression($this->integerOnly ? $this->integerPattern : $this->numberPattern),
			'message' => Html::encode(strtr($this->message, array(
				'{attribute}' => $label,
				'{value}' => $value,
			))),
		);
w  
Qiang Xue committed
133

w  
Qiang Xue committed
134
		if ($this->min !== null) {
135 136
			$options['min'] = $this->min;
			$options['tooSmall'] = Html::encode(strtr($this->tooSmall, array(
Qiang Xue committed
137
				'{attribute}' => $label,
138
				'{value}' => $value,
Qiang Xue committed
139
				'{min}' => $this->min,
140
			)));
w  
Qiang Xue committed
141
		}
w  
Qiang Xue committed
142
		if ($this->max !== null) {
143 144
			$options['max'] = $this->max;
			$options['tooBig'] = Html::encode(strtr($this->tooBig, array(
Qiang Xue committed
145
				'{attribute}' => $label,
146
				'{value}' => $value,
Qiang Xue committed
147
				'{max}' => $this->max,
148
			)));
w  
Qiang Xue committed
149
		}
Qiang Xue committed
150
		if ($this->skipOnEmpty) {
151
			$options['skipOnEmpty'] = 1;
w  
Qiang Xue committed
152 153
		}

154
		$view->registerAssetBundle('yii/validation');
155
		return 'yii.validation.number(value, messages, ' . Json::encode($options) . ');';
w  
Qiang Xue committed
156
	}
Zander Baldwin committed
157
}