API
@-Formulas
JavaScript
LotusScript
Reg Exp
Web Design
Notes Client
XPages
 
Is Valid Zip Code
This regular expression will validate a US zip code, which can be either 5 numbers. Or 5 numbers, plus a dash, then 4 more numbers.

function isValidZipCode(value) {
   var re = /^\d{5}([\-]\d{4})?$/;
   return (re.test(value));
}

The regular expression doesn't need a lot of explanation. ^\d{5} says that the regular expression must start ("^") with exactly five ("{5}") digits ("\d"). ([\-]\d{4})?$ says that the grouping (in parentheses) can appear either zero or one time ("?") and must be the end of the string ("$"). Inside the grouping is the literal dash character ("-", but since that character normally means other things in regular expressions, it needs to be "escaped" with the slash in front). After the dash is exactly four ("{4}") digits ("\d").

So, a value of "12345" will succeed. Any letter will cause the expression to fail. A value of "12345-6789" will succeed. If the 9 digit format is used, then the previous format (5 digits, dash, 4 digits) must be used. Other formats will fail.