NumberValidator
API reference › yii › validators › NumberValidator
NumberValidator validates that the attribute value is a number.
The format of the number must match the regular expression specified in $integerPattern or $numberPattern.
Optionally, you may configure the $max and $min properties to ensure the number
is within certain range.
Properties
Section titled “Properties”| Property | Type | Description | Defined by |
|---|---|---|---|
$allowArray | bool | Whether to allow array type attribute. Default: false. Available since 2.0.42. | NumberValidator |
$attributeNames read-only | array | Attribute names. | Validator |
$attributes | array| | Attributes to be validated by this validator. Default: []. | Validator |
$behaviors read-only | array<yii\<static>> | List of behaviors attached to this component. | yii\ |
$builtInValidators static | array | List of built-in validators (name => class or configuration) Default: ['boolean' => 'yii\. | Validator |
$clientScript | array|yii\| | Client script class to use for client-side validation. Default: null. | NumberValidator |
$enableClientValidation | bool | Whether to enable client-side validation for this validator. Default: true. | Validator |
$except | array| | Scenarios that the validator should not be applied to. Default: []. | Validator |
$integerOnly | bool | Whether the attribute value can only be an integer. Default: false. | NumberValidator |
$integerPattern | string | The regular expression for matching integers. Default: '/^[+-]?\. | NumberValidator |
$isEmpty | callable| | A PHP callable that replaces the default implementation of isEmpty(). Default: null. | Validator |
$max | int| | Upper limit of the number. Default: null. | NumberValidator |
$message | string| | The user-defined error message. Default: null. | Validator |
$min | int| | Lower limit of the number. Default: null. | NumberValidator |
$numberPattern | string | The regular expression for matching numbers. Default: '/^[-+]?[0-9]*\. | NumberValidator |
$on | array| | Scenarios that the validator can be applied to. Default: []. | Validator |
$skipOnEmpty | bool | Whether this validation rule should be skipped if the attribute value is null or an empty string. Default: true. | Validator |
$skipOnError | bool | Whether this validation rule should be skipped if the attribute being validated already has some validation error according to some previous rules. Default: true. | Validator |
$tooBig | string | User-defined error message used when the value is bigger than $max. Default: null. | NumberValidator |
$tooSmall | string | User-defined error message used when the value is smaller than $min. Default: null. | NumberValidator |
$validationAttributes read-only | array| | List of attribute names. | Validator |
$when | callable| | A PHP callable whose return value determines whether this validator should be applied. Default: null. | Validator |
$whenClient | string| | A JavaScript function name whose return value determines whether this validator should be applied on the client-side. Default: null. | Validator |
Methods
Section titled “Methods”| Method | Description | Defined by |
|---|---|---|
__construct() | Constructor. | yii\ |
__call() | Calls the named method which is not a class method. | yii\ |
__clone() | This method is called after the object is created by cloning an existing one. | yii\ |
__get() | Returns the value of a component property. | yii\ |
__isset() | Checks if a property is set, i.e. defined and not null. | yii\ |
__set() | Sets the value of a component property. | yii\ |
__unset() | Sets a component property to be null. | yii\ |
addError() | Adds an error about the specified attribute to the model object. | Validator |
attachBehavior() | Attaches a behavior to this component. | yii\ |
attachBehaviors() | Attaches a list of behaviors to the component. | yii\ |
behaviors() | Returns a list of behaviors that this component should behave as. | yii\ |
canGetProperty() | Returns a value indicating whether a property can be read. | yii\ |
canSetProperty() | Returns a value indicating whether a property can be set. | yii\ |
className() static | Returns the fully qualified name of this class. | yii\ |
clientValidateAttribute() | Returns the JavaScript needed for performing client-side validation. | NumberValidator |
createValidator() static | Creates a validator object. | Validator |
detachBehavior() | Detaches a behavior from the component. | yii\ |
detachBehaviors() | Detaches all behaviors from the component. | yii\ |
ensureBehaviors() | Makes sure that the behaviors declared in behaviors() are attached to this component. | yii\ |
getAttributeNames() | Returns cleaned attribute names without the ! character at the beginning. | Validator |
getBehavior() | Returns the named behavior object. | yii\ |
getBehaviors() | Returns all behaviors attached to this component. | yii\ |
getClientOptions() | Returns the client-side validation options. | NumberValidator |
getFormattedClientMessage() | Returns the formatted validation message for client-side validation. | Validator |
getValidationAttributes() | Returns a list of attributes this validator applies to. | Validator |
hasEventHandlers() | Returns a value indicating whether there is any handler attached to the named event. | yii\ |
hasMethod() | Returns a value indicating whether a method is defined. | yii\ |
hasProperty() | Returns a value indicating whether a property is defined for this component. | yii\ |
init() | Initializes the object. | NumberValidator |
isActive() | Returns a value indicating whether the validator is active for the given scenario and attribute. | Validator |
isEmpty() | Checks if the given value is empty. | Validator |
off() | Detaches an existing event handler from this component. | yii\ |
on() | Attaches an event handler to an event. | yii\ |
trigger() | Triggers an event. | yii\ |
validate() | Validates a given value. | Validator |
validateAttribute() | Validates a single attribute. | NumberValidator |
validateAttributes() | Validates the specified object. | Validator |
formatMessage() protected | Formats a mesage using the I18N, or simple strtr if \ is not available. | Validator |
validateValue() protected | Validates a value. | NumberValidator |
Property details
Section titled “Property details”$allowArray
Section titled “$allowArray ”public bool $allowArray = falseWhether to allow array type attribute.
Defaults to false.
Since
2.0.42
$integerOnly
Section titled “$integerOnly ”public bool $integerOnly = falseWhether the attribute value can only be an integer.
Defaults to false.
public int|float|null $max = nullUpper limit of the number.
Defaults to null, meaning no upper limit.
public int|float|null $min = nullLower limit of the number.
Defaults to null, meaning no lower limit.
$numberPattern
Section titled “$numberPattern ”public string $numberPattern = '/^[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?$/'The regular expression for matching numbers.
It defaults to a pattern that matches floating numbers with optional exponential part (e.g. -1.23e-10).
Method details
Section titled “Method details”clientValidateAttribute()
Section titled “clientValidateAttribute() ”public function clientValidateAttribute(mixed $model, mixed $attribute, mixed $view): string|nullReturns the JavaScript needed for performing client-side validation.
Calls getClientOptions() to generate options array for client-side validation.
You may override this method to return the JavaScript validation code if the validator can support client-side validation.
The following JavaScript variables are predefined and can be used in the validation code:
attribute: an object describing the the attribute being validated.value: the value being validated.messages: an array used to hold the validation error messages for the attribute.deferred: an array used to hold deferred objects for asynchronous validation$form: a jQuery object containing the form element
The attribute object contains the following properties:
id: a unique ID identifying the attribute (e.g. “loginform-username”) in the formname: attribute name or expression (e.g. “[0]content” for tabular input)container: the jQuery selector of the container of the input fieldinput: the jQuery selector of the input field under the context of the formerror: the jQuery selector of the error tag under the context of the containerstatus: status of the input field, 0: empty, not entered before, 1: validated, 2: pending validation, 3: validating
Parameters
| Parameter | Type | Description |
|---|---|---|
$model | mixed | The data model being validated |
$attribute | mixed | The name of the attribute to be validated. |
$view | mixed | The view object that is going to be used to render views or view files containing a model form with this validator applied. |
Returns
string|null: The client-side validation script. Null if the validator does not support client-side validation.
getClientOptions()
Section titled “getClientOptions() ”public function getClientOptions(mixed $model, mixed $attribute): arrayReturns the client-side validation options.
This method is usually called from clientValidateAttribute(). You may override this method to modify options
that will be passed to the client-side validation.
Parameters
| Parameter | Type | Description |
|---|---|---|
$model | mixed | The model being validated |
$attribute | mixed | The attribute name being validated |
Returns
array: The client-side validation options
Since
2.0.11
init()
Section titled “init() ”public function init(): mixedInitializes the object.
This method is invoked at the end of the constructor after the object is initialized with the given configuration.
Returns
mixed
validateAttribute()
Section titled “validateAttribute() ”public function validateAttribute(mixed $model, mixed $attribute): mixedValidates a single attribute.
Child classes must implement this method to provide the actual validation logic.
Parameters
| Parameter | Type | Description |
|---|---|---|
$model | mixed | The data model to be validated |
$attribute | mixed | The name of the attribute to be validated. |
Returns
mixed
validateValue()
Section titled “validateValue() ”protected function validateValue(mixed $value): array|nullValidates a value.
A validator class can implement this method to support data validation out of the context of a data model.
Parameters
| Parameter | Type | Description |
|---|---|---|
$value | mixed | The data value to be validated. |
Returns
array|null: The error message and the array of parameters to be inserted into the error message. if (!$valid) { return [$this->message, [ ‘param1’ => $this->param1, ‘formattedLimit’ => Yii::$app->formatter->asShortSize($this->getSizeLimit()), ‘mimeTypes’ => implode(’, ’, $this->mimeTypes), ‘param4’ => ‘etc…’, ]]; } return null; for this example message template can contain {param1}, {formattedLimit}, {mimeTypes}, {param4} Null should be returned if the data is valid.
Throws
yii\base\NotSupportedException: if the validator does not supporting data validation without a model