Saturday, July 26, 2008

isValidIP

As promised, more regular expression fun. This week we're going to validate IP addresses. An IP address consists of four octets separated by periods. A lazy person might be inclined to use a regular expression of \d{1,3} for each octet, but that would allow numbers larger than 255. A more complex expression is needed: ([1]?\d{1,2}|2[0-4]{1}\d{1}|25[0-5]{1}).


This expression consists of three parts separated by the pipe character "|". The first part, [1]?\d{1,2}, matches numbers between 0 and 199. The second part, 2[0-4]{1}\d{1}, matches numbers between 200 and 249. The third part, 25[0-5]{1}, matches numbers between 250 and 255. We will repeat this pattern four times, once for each octet, and separate with periods.


ASP

  1. function isValidIP(ip)
  2.     dim regEx
  3.     set regEx = new RegExp
  4.     with regEx
  5.         .IgnoreCase = True
  6.         .Global = True
  7.         .Pattern = "^([1]?\d{1,2}|2[0-4]{1}\d{1}|25[0-5]{1})(\.([1]?\d{1,2}|2[0-4]{1}\d{1}|25[0-5]{1})){3}$"
  8.     end with
  9.     if regEx.Test(trim(CStr(ip))) then
  10.         isValidIP = true
  11.     else
  12.         isValidIP = false
  13.     end if
  14.     set regEx = nothing
  15. end function

PHP

  1. function isValidIP($ip)
  2. {
  3.     $pattern = "/^([1]?\d{1,2}|2[0-4]{1}\d{1}|25[0-5]{1})(\.([1]?\d{1,2}|2[0-4]{1}\d{1}|25[0-5]{1})){3}$/";
  4.     return (preg_match($pattern, $ip) > 0) ? true : false;
  5. }

Next week we're going to build on this pattern to validate something else. I wonder what that could be?


No comments: