View Javadoc
1   package ejava.jpa.example.validation;
2   
3   import java.util.Calendar;
4   import java.util.Date;
5   import java.util.GregorianCalendar;
6   
7   import javax.validation.ConstraintValidator;
8   import javax.validation.ConstraintValidatorContext;
9   
10  public class MinAgeValidator implements ConstraintValidator<MinAge, Date>{
11  	int minAge;
12  
13  	@Override
14  	public void initialize(MinAge constraint) {
15  		this.minAge = constraint.age();
16  	}
17  
18  	@Override
19  	public boolean isValid(Date date, ConstraintValidatorContext ctx) {
20  		if (date==null) { return true; }
21  		//get today's date
22  		Calendar latestBirthDate = new GregorianCalendar();
23  		//determine min date that meets age requirement
24  		latestBirthDate.add(Calendar.YEAR, -1*minAge);
25  		
26  		//get calendate date of object
27  		Calendar birthDate = new GregorianCalendar();
28  		birthDate.setTime(date);
29  
30  		//return whether meets criteria
31  		if (birthDate.after(latestBirthDate)) {
32  			String errorMsg = String.format("%d is younger than minimum %d", 
33  					getAge(birthDate), 
34  					minAge);
35  			ctx.buildConstraintViolationWithTemplate(errorMsg)
36  				.addConstraintViolation();
37  			return false;
38  		} else {
39  			return true;
40  		}
41  	}
42  	
43  	private int getAge(Calendar birth) {
44  		Calendar now = new GregorianCalendar();
45  		int years = now.get(Calendar.YEAR) - birth.get(Calendar.YEAR);
46  		int months = now.get(Calendar.MONTH) - birth.get(Calendar.MONTH);
47  		if (months < 0) { years -= 1; }
48  		else if (months==0) {
49  			int days = now.get(Calendar.DAY_OF_YEAR) - birth.get(Calendar.DAY_OF_YEAR);
50  			if (days < 0) { years -= 1; }
51  		}
52  		return years;
53  	}
54  }