IPValidator checks if an IP address is technically correct.
Documentation ¶
Requirements ¶
- Yii 1.0 or above
Installation ¶
- Extract the release file under
protected/extensions
Usage ¶
The following model code validates against the ipv4 regex:
public function rules()
{
return array(
array('ipAddr', 'application.extensions.ipvalidator.IPValidator', 'version' => 'v4')
);
}
While the following validates against the ipv6 regex: [php] public function rules() { return array(
array('ipAddr', 'application.extensions.ipvalidator.IPValidator', 'version' => 'v4')
);
}
Change Log ¶
1.1 - ipv4 bug fixed (Thanks to beesnept)
- ipv6 support added (Thanks to Rich Brown for his regex)
1.0 - initial version
Regexp error
I'm sorry I mispelled the syntax, the correct regexp is:
/^(([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$/
Regexp error
The regular expression is not correct, as it considers IP addresses like 10a0a0a1 as valid.
We need to use . instead of . to match for the dot character so we have to change the regular expression to
/^(([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]).){3}([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$/
Allow both
I made a patch for allowing both standars (v4 or v6):
--- IPValidator.php.old 2010-06-11 22:03:25.000000000 -0300 +++ IPValidator.php 2012-02-27 14:16:26.587519647 -0300 @@ -10,6 +10,7 @@ public $allowEmpty = true; + // May be v4 or v6. If empty it allows any of them. public $version = 'v4'; protected function validateAttribute($object,$attribute) @@ -17,8 +18,15 @@ $value=$object->$attribute; if($this->allowEmpty && ($value===null || $value==='')) return; + + if(in_array(strtolower($this->version), array("v4",""))) + $validV4 = $valid = preg_match($this->v4pattern,$value); + + if(in_array(strtolower($this->version), array("v6",""))) + $validV6 = $valid = preg_match($this->v6pattern, $value); - $valid = (strtolower($this->version) === 'v6') ? preg_match($this->v6pattern, $value) : preg_match($this->v4pattern,$value); + if($this->version === "") + $valid = $validV4 || $validV6; if(!$valid) { @@ -27,4 +35,3 @@
Hope it helps.
If you have any questions, please ask in the forum instead.
Signup or Login in order to comment.