Skip to content

Commit

Permalink
validate ip from subnet
Browse files Browse the repository at this point in the history
  • Loading branch information
eredi93 committed Jun 7, 2016
1 parent f2fe603 commit 2c3f604
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 1 deletion.
29 changes: 28 additions & 1 deletion src/Validators/IPAddress.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,17 +26,44 @@ class IPAddress extends Filter
*
* @param bool $IPv4 Filter only IPv4 addresses
* @param bool $IPv6 Filter only IPv6 addresses
* @param bool $no_priv_range Address not in private range
* @param string $message Message returned on validation error
* @return void
*/
public function __construct($IPv4 = true, $IPv6 = false, $message = "The field must be a valid IP Address.")
public function __construct($IPv4 = true, $IPv6 = false, $no_priv_range = false,
$message = "The field must be a valid IP Address.")
{
parent::__construct($message);
$this->filterFlag = FILTER_VALIDATE_IP;
if ($IPv4) {
$this->filterOptions = FILTER_FLAG_IPV4;
} elseif ($IPv6) {
$this->filterOptions = FILTER_FLAG_IPV6;
} elseif ($no_priv_range) {
$this->filterOptions = FILTER_FLAG_NO_PRIV_RANGE;
}
}

/**
* Check if value passes the validation
*
* @param string $value Value to check
* @return bool
*/
public function check($value)
{
if (strpos($value, "/")) {
$value = explode("/", $value)[0];
}
if ($this->filterOptions) {
$filter = filter_var($value, $this->filterFlag, $this->filterOptions);
} else {
$filter = filter_var($value, $this->filterFlag);
}
if ($filter) {
return true;
}
$this->setError($this->message);
return false;
}
}
1 change: 1 addition & 0 deletions tests/Validators/IPAddressTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ public function testIPAddress()
$ip = new \Forms\Validators\IPAddress();

$this->assertTrue($ip->check('8.8.8.8'), "IPAddress did not validate correctly.");
$this->assertTrue($ip->check('10.10.5.45/32'), "IPAddress did not validate correctly.");
$this->assertFalse($ip->check('10.10.10.300'), "IPAddress did not validate correctly.");
$this->assertEquals("The field must be a valid IP Address.", $ip->getError(),"");
}
Expand Down

0 comments on commit 2c3f604

Please sign in to comment.