Saturday, August 9, 2008

isValidZipCode

Another week, another validation function. Last week was a little long, so this week we'll do a bit shorter one: validating a United States ZIP code. The pattern is simple enough that I don't think an explanation is warranted.


ASP

  1. function isValidZIPCode(zipCode)
  2.     dim regEx
  3.     set regEx = new RegExp
  4.     with regEx
  5.         .IgnoreCase = True
  6.         .Global = True
  7.         .Pattern = "^[0-9]{5}(-[0-9]{4})?$"
  8.     end with
  9.     if regEx.Test(trim(CStr(zipCode))) then
  10.         isValidZipCode = True
  11.     else
  12.         isValidZipCode = False
  13.     end if
  14.     set regEx = nothing
  15. end function

PHP

  1. function isValidZIPCode($zipCode)
  2. {
  3.     return (preg_match("/^[0-9]{5}(-[0-9]{4})?$/i", trim($zipCode)) > 0) ? true : false;
  4. }

No comments: