package com.yhbc.validation; import static java.lang.annotation.ElementType.ANNOTATION_TYPE; import static java.lang.annotation.ElementType.CONSTRUCTOR; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.ElementType.PARAMETER; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; import javax.validation.Constraint; import javax.validation.Payload; import javax.validation.ReportAsSingleViolation; /** * 日期格式驗證,能夠在{@code format}中添加有效的日期格式 * @author Canaan * @date 2017年3月8日 */ @Documented @Constraint(validatedBy = { DateValueValidator.class }) @Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER }) @Retention(RUNTIME) @ReportAsSingleViolation public @interface DateValue { String message() default "日期格式不正確"; Class<?>[] groups() default { }; Class<? extends Payload>[] payload() default { }; /** * 有效的日期格式 */ String[] format() default {}; /** * Defines several {@link DateValue} annotations on the same element. * * @see com.yhbc.validation.DateValue.DateValue */ @Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER }) @Retention(RUNTIME) @Documented @interface List { DateValue[] value(); } }
package com.yhbc.validation; import java.text.SimpleDateFormat; import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; public class DateValueValidator implements ConstraintValidator<DateValue, String> { private String[] formats; @Override public void initialize(DateValue constraintAnnotation) { formats = constraintAnnotation.format(); } @Override public boolean isValid(String value, ConstraintValidatorContext context) { if(value==null || "".equals(value.trim())){return true;} if(formats.length==0){return true;} for (String string : formats) { try{ SimpleDateFormat formatter = new SimpleDateFormat(string); formatter.parse(value); }catch(Exception e){ return false; } } return true; } }