Yii 1.1: ipvalidator

IP Syntax Validation (ipv4/ipv6)
4 followers

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

Total 3 comments

#7143 report it
Renan at 2012/02/27 12:25pm
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.

#1201 report it
beesnept at 2009/10/29 04:52am
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])$/
#1202 report it
beesnept at 2009/10/29 04:42am
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])$/

Leave a comment

Please to leave your comment.

Create extension
  • Yii Version: 1.1
  • License: Other Open Source License
  • Developed by: eval
  • Category: Validation
  • Votes: +4
  • Downloaded: 1,453 times
  • Created on: Nov 26, 2008
  • Last updated: Jun 11, 2010