时间格式 注解 验证

EnumValid.java

1
2
3
4
5
6
7
8
9
10
11
12
13

@Constraint(validatedBy = DateFormatValidator.class)
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface DateFormat {
String message() default "";

String pattern() default "yyyy-MM-dd HH:mm:ss";

Class<?>[] groups() default {};

Class<? extends Payload>[] payload() default {};
}

校验器EnumValidator.java

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;
}

}

使用的时候,注解作用在DTO字段上:

1
2
3
4
5
public class RequestDto {

@DateFormat(pattern = "yyyy-MM-dd")
private String data;
}

评论