1 7 package com.inversoft.util.typevalidator; 8 9 10 import java.util.Locale ; 11 12 13 22 public class ZipcodeTypeValidator extends BaseTypeValidator { 23 24 28 public static final String DEFAULT_MESSAGE = "Invalid zip code"; 29 30 31 34 public ZipcodeTypeValidator() { 35 } 37 38 39 43 protected String internalValidate(Object value, Object params, String message, 44 Locale locale, Object [] mesgParams) { 45 if (locale == null) { 46 locale = Locale.getDefault(); 47 } 48 49 String error = null; 50 if (locale.getCountry().equals("US") || locale.getCountry().equals("UM")) { 51 error = internalValidateUS(value, params, message, mesgParams); 52 } 53 54 return error; 55 } 56 57 61 private String internalValidateUS(Object value, Object params, String message, 62 Object [] mesgParams) { 63 String error = null; 64 65 StringBuffer numberBuf = new StringBuffer (); 67 String localNumber = value.toString().trim(); 68 char ch; 69 boolean valid = true; 70 boolean dashFound = false; 71 for (int i = 0; i < localNumber.length(); i++) { 72 ch = localNumber.charAt(i); 73 if (Character.isDigit(ch)) { 74 numberBuf.append(ch); 75 } else if (ch == '-') { 76 numberBuf.append(ch); 77 if (dashFound) { 78 valid = false; 79 break; 80 } 81 dashFound = true; 82 } else if (ch != ' ') { 83 valid = false; 84 break; 85 } 86 } 87 88 if (valid) { 89 int length = numberBuf.length(); 90 int dash = numberBuf.indexOf("-"); 91 if (length == 5 || length == 9) { 92 valid = (dash == -1); 93 } else if (length == 10) { 94 valid = (dash == 5); 95 } else { 96 valid = false; 97 } 98 } 99 100 if (!valid) { 101 error = getErrorMessage(message, DEFAULT_MESSAGE, mesgParams); 102 } 103 104 return error; 105 } 106 } | Popular Tags |