View Javadoc

1   /*
2    * Copyright (C) 2007 Alf Mikula
3    * 
4    * This file is part of PromoteGo.
5    *
6    * PromoteGo is free software: you can redistribute it and/or modify
7    * it under the terms of the GNU General Public License as published by
8    * the Free Software Foundation, either version 3 of the License, or
9    * (at your option) any later version.
10   *
11   * PromoteGo is distributed in the hope that it will be useful,
12   * but WITHOUT ANY WARRANTY; without even the implied warranty of
13   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14   * GNU General Public License for more details.
15   *
16   * You should have received a copy of the GNU General Public License
17   * along with PromoteGo.  If not, see <http://www.gnu.org/licenses/>.
18   */
19  package org.promotego.validators;
20  
21  import org.promotego.beans.Address;
22  import org.springframework.validation.Errors;
23  import org.springframework.validation.ValidationUtils;
24  import org.springframework.validation.Validator;
25  
26  public class AddressValidator implements Validator
27  {
28      private String m_prefix = null;
29      
30      public AddressValidator()
31      {
32          m_prefix = "";
33      }
34      
35      public AddressValidator(String prefix)
36      {
37          m_prefix = prefix + ".";
38      }
39      
40      public boolean supports(@SuppressWarnings("unchecked") Class clazz)
41      {
42          return Address.class.isAssignableFrom(clazz);
43      }
44  
45      public void validate(Object target, Errors errors)
46      {
47          if (m_prefix != null)
48          {
49              // Address is embedded in another object -- name not required.
50              ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name", "required", "Field is required.");
51          }
52          
53          Address address = (Address)target;
54          
55          // Confirm either zip or city+state
56          if (notEmpty(address.getPostalCode()))
57          {
58              // TODO Confirm either 5 digits or 5-4 digits
59          }
60          else if (notEmpty(address.getCity()) && notEmpty(address.getState()))
61          {
62              // TODO Confirm state
63          }
64          else
65          {
66              errors.rejectValue(m_prefix + "postalCode", "minimumAddress", "Address must contain at least a zip code or city and state");
67          }
68      }
69  
70      private boolean notEmpty(String testString)
71      {
72          return testString != null && testString.length() > 0;
73      }
74  }