0 Replies - 218 Views - Last Post: 16 April 2008 - 09:08 AM

#1 PsychoCoder   User is offline

  • Google.Sucks.Init(true);
  • member icon

Reputation: 1659
  • View blog
  • Posts: 19,853
  • Joined: 26-July 07

Validate US zip code with Regular Expressions

Posted 16 April 2008 - 09:08 AM

Description: Add a reference to System.Text.RegularExpressions, then pass your string to the method. Returns true or falseThis is a snippet I use whenever I need to validate a US zip code. The pattern allows for 1) 5 digit zip codes 2) 5 + 4 digit zip codes 3) 9 digit zip codes
//Namespace Reference
using System.Text.RegularExpressions

/// 
/// method for validating a US zip code
/// 
/// zip code to validate
/// true/false
public static bool IsValidUSZip(string num)
{
    // Allows 5 digit, 5+4 digit and 9 digit zip codes
    string pattern = @"^(d{5}-d{4}|d{5}|d{9})$";
    Regex match = new Regex(pattern);
    return match.IsMatch(num);
}


Is This A Good Question/Topic? 0
  • +

Page 1 of 1