Skip to content
PHP Ecosystem
Explore

IpValidator

API reference › yii › validators › IpValidator

classyii\validators\IpValidator
ExtendsValidator » yii\base\Component » yii\base\BaseObject
Implementsyii\base\Configurable
Since2.0.7
Sourceframework/validators/IpValidator.php

The validator checks if the attribute value is a valid IPv4/IPv6 address or subnet.

It also may change attribute’s value if normalization of IPv6 expansion is enabled.

The following are examples of validation rules using this validator:

['ip_address', 'ip'], // IPv4 or IPv6 address
['ip_address', 'ip', 'ipv6' => false], // IPv4 address (IPv6 is disabled)
['ip_address', 'ip', 'subnet' => true], // requires a CIDR prefix (like 10.0.0.1/24) for the IP address
['ip_address', 'ip', 'subnet' => null], // CIDR prefix is optional
['ip_address', 'ip', 'subnet' => null, 'normalize' => true], // CIDR prefix is optional and will be added when missing
['ip_address', 'ip', 'ranges' => ['192.168.0.0/24']], // only IP addresses from the specified subnet are allowed
['ip_address', 'ip', 'ranges' => ['!192.168.0.0/24', 'any']], // any IP is allowed except IP in the specified subnet
['ip_address', 'ip', 'expandIPv6' => true], // expands IPv6 address to a full notation format
PropertyTypeDescriptionDefined by
$attributeNames read-onlyarrayAttribute names.Validator
$attributesarray|stringAttributes to be validated by this validator. Default: [].Validator
$behaviors read-onlyarray<yii\base\Behavior<static>>List of behaviors attached to this component.yii\base\Component
$builtInValidators staticarrayList of built-in validators (name => class or configuration) Default: ['boolean' => 'yii\validators\BooleanValidator', 'captcha' => 'yii\captcha\CaptchaValidator', 'compare' => 'yii\validators\CompareValidator', 'date' => 'yii\validators\DateValidator', 'datetime' => ['class' => 'yii\validators\DateValidator', 'type' => \yii\validators\DateValidator::TYPE_DATETIME], 'time' => ['class' => 'yii\validators\DateValidator', 'type' => \yii\validators\DateValidator::TYPE_TIME], 'default' => 'yii\validators\DefaultValueValidator', 'double' => 'yii\validators\NumberValidator', 'each' => 'yii\validators\EachValidator', 'email' => 'yii\validators\EmailValidator', 'exist' => 'yii\validators\ExistValidator', 'file' => 'yii\validators\FileValidator', 'filter' => 'yii\validators\FilterValidator', 'image' => 'yii\validators\ImageValidator', 'in' => 'yii\validators\RangeValidator', 'integer' => ['class' => 'yii\validators\NumberValidator', 'integerOnly' => true], 'match' => 'yii\validators\RegularExpressionValidator', 'number' => 'yii\validators\NumberValidator', 'required' => 'yii\validators\RequiredValidator', 'safe' => 'yii\validators\SafeValidator', 'string' => 'yii\validators\StringValidator', 'trim' => ['class' => 'yii\validators\TrimValidator', 'skipOnArray' => true], 'unique' => 'yii\validators\UniqueValidator', 'url' => 'yii\validators\UrlValidator', 'ip' => 'yii\validators\IpValidator'].Validator
$clientScriptarray|yii\validators\client\ClientValidatorScriptInterface|nullClient script class to use for client-side validation. Default: null.IpValidator
$enableClientValidationboolWhether to enable client-side validation for this validator. Default: true.Validator
$exceptarray|stringScenarios that the validator should not be applied to. Default: [].Validator
$expandIPv6boolWhether to expand an IPv6 address to the full notation format. Default: false.IpValidator
$hasSubnetstringUser-defined error message is used when validation fails due to $subnet is false, but CIDR prefix is present. Default: null.IpValidator
$ipv4boolWhether the validating value can be an IPv4 address. Default: true.IpValidator
$ipv4NotAllowedstringUser-defined error message is used when validation fails due to the disabled IPv4 validation. Default: null.IpValidator
$ipv4PatternstringRegexp-pattern to validate IPv4 address Default: '/^(?:(?:2(?:[0-4]\d|5[0-5])|[0-1]?\d?\d)\.){3}(?:(?:2([0-4]\d|5[0-5])|[0-1]?\d?\d))$/'.IpValidator
$ipv6boolWhether the validating value can be an IPv6 address. Default: true.IpValidator
$ipv6NotAllowedstringUser-defined error message is used when validation fails due to the disabled IPv6 validation. Default: null.IpValidator
$ipv6PatternstringRegexp-pattern to validate IPv6 address Default: '/^(([\da-fA-F]{1,4}:){7}[\da-fA-F]{1,4}|([\da-fA-F]{1,4}:){1,7}:|([\da-fA-F]{1,4}:){1,6}:[\da-fA-F]{1,4}|([\da-fA-F]{1,4}:){1,5}(:[\da-fA-F]{1,4}){1,2}|([\da-fA-F]{1,4}:){1,4}(:[\da-fA-F]{1,4}){1,3}|([\da-fA-F]{1,4}:){1,3}(:[\da-fA-F]{1,4}){1,4}|([\da-fA-F]{1,4}:){1,2}(:[\da-fA-F]{1,4}){1,5}|[\da-fA-F]{1,4}:((:[\da-fA-F]{1,4}){1,6})|:((:[\da-fA-F]{1,4}){1,7}|:)|fe80:(:[\da-fA-F]{0,4}){0,4}%[\da-zA-Z]+|::(ffff(:0{1,4})?:)?((25[0-5]|(2[0-4]|1?\d)?\d)\.){3}(25[0-5]|(2[0-4]|1?\d)?\d)|([\da-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1?[\d])?\d)\.){3}(25[0-5]|(2[0-4]|1?\d)?\d))$/'.IpValidator
$isEmptycallable|nullA PHP callable that replaces the default implementation of isEmpty(). Default: null.Validator
$messagestringUser-defined error message is used when validation fails due to the wrong IP address format. Default: null.IpValidator
$negationboolWhether address may have a NEGATION_CHAR character at the beginning. Default: false.IpValidator
$networksarrayThe network aliases, that can be used in $ranges. - key - alias name - value - array of strings. Default: ['*' => ['any'], 'any' => ['0.0.0.0/0', '::/0'], 'private' => ['10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16', 'fd00::/8'], 'multicast' => ['224.0.0.0/4', 'ff00::/8'], 'linklocal' => ['169.254.0.0/16', 'fe80::/10'], 'localhost' => ['127.0.0.0/8', '::1'], 'documentation' => ['192.0.2.0/24', '198.51.100.0/24', '203.0.113.0/24', '2001:db8::/32'], 'system' => ['multicast', 'linklocal', 'localhost', 'documentation']].IpValidator
$normalizeboolWhether to add the CIDR prefix with the smallest length (32 for IPv4 and 128 for IPv6) to an address without it. Default: false.IpValidator
$noSubnetstring|nullUser-defined error message is used when validation fails due to subnet $subnet set to ‘only’, but the CIDR prefix is not set. Default: null.IpValidator
$notInRangestringUser-defined error message is used when validation fails due to IP address is not not allowed by $ranges check. Default: null.IpValidator
$onarray|stringScenarios that the validator can be applied to. Default: [].Validator
$rangesarray|string|nullThe IPv4 or IPv6 ranges that are allowed or forbidden.IpValidator
$skipOnEmptyboolWhether this validation rule should be skipped if the attribute value is null or an empty string. Default: true.Validator
$skipOnErrorboolWhether this validation rule should be skipped if the attribute being validated already has some validation error according to some previous rules. Default: true.Validator
$subnetbool|nullWhether the address can be an IP with CIDR subnet, like 192.168.10.0/24. Default: false.IpValidator
$validationAttributes read-onlyarray|nullList of attribute names.Validator
$whencallable|nullA PHP callable whose return value determines whether this validator should be applied. Default: null.Validator
$whenClientstring|nullA JavaScript function name whose return value determines whether this validator should be applied on the client-side. Default: null.Validator
$wrongCidrstringUser-defined error message is used when validation fails due to the wrong CIDR. Default: null.IpValidator
MethodDescriptionDefined by
__construct()Constructor.yii\base\BaseObject
__call()Calls the named method which is not a class method.yii\base\Component
__clone()This method is called after the object is created by cloning an existing one.yii\base\Component
__get()Returns the value of a component property.yii\base\Component
__isset()Checks if a property is set, i.e. defined and not null.yii\base\Component
__set()Sets the value of a component property.yii\base\Component
__unset()Sets a component property to be null.yii\base\Component
addError()Adds an error about the specified attribute to the model object.Validator
attachBehavior()Attaches a behavior to this component.yii\base\Component
attachBehaviors()Attaches a list of behaviors to the component.yii\base\Component
behaviors()Returns a list of behaviors that this component should behave as.yii\base\Component
canGetProperty()Returns a value indicating whether a property can be read.yii\base\Component
canSetProperty()Returns a value indicating whether a property can be set.yii\base\Component
className() staticReturns the fully qualified name of this class.yii\base\BaseObject
clientValidateAttribute()Returns the JavaScript needed for performing client-side validation.IpValidator
createValidator() staticCreates a validator object.Validator
detachBehavior()Detaches a behavior from the component.yii\base\Component
detachBehaviors()Detaches all behaviors from the component.yii\base\Component
ensureBehaviors()Makes sure that the behaviors declared in behaviors() are attached to this component.yii\base\Component
getAttributeNames()Returns cleaned attribute names without the ! character at the beginning.Validator
getBehavior()Returns the named behavior object.yii\base\Component
getBehaviors()Returns all behaviors attached to this component.yii\base\Component
getClientOptions()Returns the client-side validation options.IpValidator
getFormattedClientMessage()Returns the formatted validation message for client-side validation.Validator
getRanges()IpValidator
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\base\Component
hasMethod()Returns a value indicating whether a method is defined.yii\base\Component
hasProperty()Returns a value indicating whether a property is defined for this component.yii\base\Component
init()Initializes the object.IpValidator
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\base\Component
on()Attaches an event handler to an event.yii\base\Component
setRanges()Set the IPv4 or IPv6 ranges that are allowed or forbidden.IpValidator
trigger()Triggers an event.yii\base\Component
validate()Validates a given value.Validator
validateAttribute()Validates a single attribute.IpValidator
validateAttributes()Validates the specified object.Validator
formatMessage() protectedFormats a mesage using the I18N, or simple strtr if \Yii::$app is not available.Validator
validateIPv4() protectedValidates IPv4 address.IpValidator
validateIPv6() protectedValidates IPv6 address.IpValidator
validateValue() protectedValidates a value.IpValidator
ConstantValueDescriptionDefined by
NEGATION_CHAR'!'Negation char.IpValidator
public bool $expandIPv6 = false

Whether to expand an IPv6 address to the full notation format.

Defaults to false.

public string $hasSubnet = null

User-defined error message is used when validation fails due to $subnet is false, but CIDR prefix is present.

You may use the following placeholders in the message:

  • {attribute}: the label of the attribute being validated
  • {value}: the value of the attribute being validated
public bool $ipv4 = true

Whether the validating value can be an IPv4 address.

Defaults to true.

public string $ipv4NotAllowed = null

User-defined error message is used when validation fails due to the disabled IPv4 validation.

You may use the following placeholders in the message:

  • {attribute}: the label of the attribute being validated
  • {value}: the value of the attribute being validated
public bool $ipv6 = true

Whether the validating value can be an IPv6 address.

Defaults to true.

public string $ipv6NotAllowed = null

User-defined error message is used when validation fails due to the disabled IPv6 validation.

You may use the following placeholders in the message:

  • {attribute}: the label of the attribute being validated
  • {value}: the value of the attribute being validated
public string $message = null

User-defined error message is used when validation fails due to the wrong IP address format.

You may use the following placeholders in the message:

  • {attribute}: the label of the attribute being validated
  • {value}: the value of the attribute being validated
public bool $negation = false

Whether address may have a NEGATION_CHAR character at the beginning.

Defaults to false.

public array $networks = ['*' => ['any'], 'any' => ['0.0.0.0/0', '::/0'], 'private' => ['10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16', 'fd00::/8'], 'multicast' => ['224.0.0.0/4', 'ff00::/8'], 'linklocal' => ['169.254.0.0/16', 'fe80::/10'], 'localhost' => ['127.0.0.0/8', '::1'], 'documentation' => ['192.0.2.0/24', '198.51.100.0/24', '203.0.113.0/24', '2001:db8::/32'], 'system' => ['multicast', 'linklocal', 'localhost', 'documentation']]

The network aliases, that can be used in $ranges. - key - alias name - value - array of strings.

String can be an IP range, IP address or another alias. String can be negated with NEGATION_CHAR (independent of negation option).

The following aliases are defined by default:

  • *: any
  • any: 0.0.0.0/0, ::/0
  • private: 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, fd00::/8
  • multicast: 224.0.0.0/4, ff00::/8
  • linklocal: 169.254.0.0/16, fe80::/10
  • localhost: 127.0.0.0/8', ::1
  • documentation: 192.0.2.0/24, 198.51.100.0/24, 203.0.113.0/24, 2001:db8::/32
  • system: multicast, linklocal, localhost, documentation
public bool $normalize = false

Whether to add the CIDR prefix with the smallest length (32 for IPv4 and 128 for IPv6) to an address without it.

Works only when subnet is not false. For example:

  • 10.0.1.5 will normalized to 10.0.1.5/32
  • 2008:db0::1 will be normalized to 2008:db0::1/128 Defaults to false.
public string|null $noSubnet = null

User-defined error message is used when validation fails due to subnet $subnet set to ‘only’, but the CIDR prefix is not set.

You may use the following placeholders in the message:

  • {attribute}: the label of the attribute being validated
  • {value}: the value of the attribute being validated
public string $notInRange = null

User-defined error message is used when validation fails due to IP address is not not allowed by $ranges check.

You may use the following placeholders in the message:

  • {attribute}: the label of the attribute being validated
  • {value}: the value of the attribute being validated
public array|string|null $ranges

The IPv4 or IPv6 ranges that are allowed or forbidden.

When the array is empty, or the option not set, all IP addresses are allowed.

Otherwise, the rules are checked sequentially until the first match is found. An IP address is forbidden, when it has not matched any of the rules.

Example:

[
'ranges' => [
'192.168.10.128'
'!192.168.10.0/24',
'any' // allows any other IP addresses
]
]

In this example, access is allowed for all the IPv4 and IPv6 addresses excluding the 192.168.10.0/24 subnet. IPv4 address 192.168.10.128 is also allowed, because it is listed before the restriction.

public bool|null $subnet = false

Whether the address can be an IP with CIDR subnet, like 192.168.10.0/24.

The following values are possible:

  • false - the address must not have a subnet (default).
  • true - specifying a subnet is required.
  • null - specifying a subnet is optional.
public string $wrongCidr = null

User-defined error message is used when validation fails due to the wrong CIDR.

You may use the following placeholders in the message:

  • {attribute}: the label of the attribute being validated
  • {value}: the value of the attribute being validated
public function clientValidateAttribute(mixed $model, mixed $attribute, mixed $view): string|null

Returns 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 form
  • name: attribute name or expression (e.g. “[0]content” for tabular input)
  • container: the jQuery selector of the container of the input field
  • input: the jQuery selector of the input field under the context of the form
  • error: the jQuery selector of the error tag under the context of the container
  • status: status of the input field, 0: empty, not entered before, 1: validated, 2: pending validation, 3: validating

Parameters

ParameterTypeDescription
$modelmixedThe data model being validated
$attributemixedThe name of the attribute to be validated.
$viewmixedThe 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.

public function getClientOptions(mixed $model, mixed $attribute): array

Returns 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

ParameterTypeDescription
$modelmixedThe model being validated
$attributemixedThe attribute name being validated

Returns

array: The client-side validation options

Since

2.0.11

public function getRanges(): array

Returns

array: The IPv4 or IPv6 ranges that are allowed or forbidden.

public function init(): mixed

Initializes the object.

This method is invoked at the end of the constructor after the object is initialized with the given configuration.

Returns

mixed

public function setRanges(array|string|null $ranges): mixed

Set the IPv4 or IPv6 ranges that are allowed or forbidden.

The following preparation tasks are performed:

  • Recursively substitutes aliases (described in $networks) with their values.
  • Removes duplicates

Parameters

ParameterTypeDescription
$rangesarray|string|nullThe IPv4 or IPv6 ranges that are allowed or forbidden. When the array is empty, or the option not set, all IP addresses are allowed. Otherwise, the rules are checked sequentially until the first match is found. An IP address is forbidden, when it has not matched any of the rules. Example: [ ‘ranges’ => [ ‘192.168.10.128’ ‘!192.168.10.0/24’, ‘any’ // allows any other IP addresses ] ] In this example, access is allowed for all the IPv4 and IPv6 addresses excluding the 192.168.10.0/24 subnet. IPv4 address 192.168.10.128 is also allowed, because it is listed before the restriction.

Returns

mixed

public function validateAttribute(mixed $model, mixed $attribute): mixed

Validates a single attribute.

Child classes must implement this method to provide the actual validation logic.

Parameters

ParameterTypeDescription
$modelmixedThe data model to be validated
$attributemixedThe name of the attribute to be validated.

Returns

mixed

protected function validateIPv4(string $value): bool

Validates IPv4 address.

Parameters

ParameterTypeDescription
$valuestring

Returns

bool

protected function validateIPv6(string $value): bool

Validates IPv6 address.

Parameters

ParameterTypeDescription
$valuestring

Returns

bool

protected function validateValue(mixed $value): array|null

Validates a value.

A validator class can implement this method to support data validation out of the context of a data model.

Parameters

ParameterTypeDescription
$valuemixedThe 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