Since there is no great tool out there, here's some code to apply some patterns to zip codes without the use of regex. You could have the patterns supplied from your servlet, but it's shown in the example for clarity.
Although your question doesn't specify a country, I will post one for US zip codes since those patterns are familiar to me:
public static boolean isProbablyValidUSZipCode(CharSequence zip) {
String[] patterns = {"#####", "#####-####", "##### ####", "#########"};
try {
for (String pattern : patterns) {
if (checkAgainstPattern(zip, pattern)) {
return true;
}
}
return false;
}
catch (NullPointerException ignored) {
return false;
}
}
private static boolean checkAgainstPattern(CharSequence s, CharSequence pattern) {
if (s.length() != pattern.length()) {
return false;
}
for (int i = 0; i < pattern.length(); i++) {
char c = s.charAt(i);
switch (pattern.charAt(i)) {
case '#':
if (!Character.isDigit(c)) {
return false;
}
break;
default:
if (c != pattern.charAt(i)) {
return false;
}
}
}
return true;
}
To allow alphanumeric, you can change Character.isDigit
to Character.isLetterOrDigit
. It will get ugly, however, if different countries have different constraints (which they do).
Of course, this will not do any sort of lookup to catch zip codes that don't exist or are somehow reserved/otherwise invalid, but it's likely better than no validation at all. If you do later find some lookup service, you can always call it after these static methods since I'd imagine that would be more expensive.