1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
| public class DateFormatValidator implements ConstraintValidator<DateFormat, String> { private String pattern;
@Override public void initialize(DateFormat dateFormat) { this.pattern = dateFormat.pattern(); }
@Override public boolean isValid(String value, ConstraintValidatorContext context) { boolean isValid = (value == null) || isValid(value); if (!isValid) { throw new RuntimeException("invalid input parameter."); } return isValid; }
private boolean isValid(String value) { boolean isValid = true; try { String time = URLDecoder.decode(value, "UTF-8"); if (pattern.length() != time.length()) { isValid = false; } else { SimpleDateFormat dateFormat = new SimpleDateFormat(pattern); dateFormat.setLenient(false); dateFormat.parse(time); } } catch (Exception e) { isValid = false; } return isValid; }
}
|