http://blog.youkuaiyun.com/neweastsun/article/details/49154337
3.1 定义注解
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD,ElementType.PARAMETER,ElementType.METHOD})
@Constraint(checkWith = CPastCheck.class)
public @interface CPast {
Stringmessage() default "日期必须小于现在.";
StringdateFormat() default "yyyy-MM-dd";
}
3.2 定义实现
public class CPastCheck extends AbstractAnnotationCheck<CPast> {
private static final longserialVersionUID = 1L;
private StringdateFormat;
public voidconfigure(final CPast constraintAnnotation) {
super.configure(constraintAnnotation);
setDateFormat(constraintAnnotation.dateFormat());
}
public booleanisSatisfied(Object validatedObject, Object valueToValidate,
OValContextcontext, Validator validator) throws OValException {
SimpleDateFormatsdf = new SimpleDateFormat(dateFormat);
if(valueToValidate instanceof String) {
try {
Datedate = sdf.parse((String) valueToValidate);
returndate.before(new Date());
}catch (ParseException e) {
e.printStackTrace();
super.setMessage("日期格式错误,无法验证,请修改成正确格式.");
returnfalse;
}
}
return false;
}
public StringgetDateFormat() {
returndateFormat;
}
public voidsetDateFormat(String dateFormat) {
this.dateFormat= dateFormat;
}
}
3.1 定义注解
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD,ElementType.PARAMETER,ElementType.METHOD})
@Constraint(checkWith = CPastCheck.class)
public @interface CPast {
Stringmessage() default "日期必须小于现在.";
StringdateFormat() default "yyyy-MM-dd";
}
3.2 定义实现
public class CPastCheck extends AbstractAnnotationCheck<CPast> {
private static final longserialVersionUID = 1L;
private StringdateFormat;
public voidconfigure(final CPast constraintAnnotation) {
super.configure(constraintAnnotation);
setDateFormat(constraintAnnotation.dateFormat());
}
public booleanisSatisfied(Object validatedObject, Object valueToValidate,
OValContextcontext, Validator validator) throws OValException {
SimpleDateFormatsdf = new SimpleDateFormat(dateFormat);
if(valueToValidate instanceof String) {
try {
Datedate = sdf.parse((String) valueToValidate);
returndate.before(new Date());
}catch (ParseException e) {
e.printStackTrace();
super.setMessage("日期格式错误,无法验证,请修改成正确格式.");
returnfalse;
}
}
return false;
}
public StringgetDateFormat() {
returndateFormat;
}
public voidsetDateFormat(String dateFormat) {
this.dateFormat= dateFormat;
}
}