와 나는 형식 YYYY-MM-DD_hh:mm:ss
유효성 검사 날짜 - 콩 검증 주석 - 특정 형식
@Past //validates for a date that is present or past. But what are the formats it accepts
그게 불가능하면 날짜를 확인하고자, 나는 @Pattern
을 사용하고 싶습니다. 그러나 @Pattern
에서 위 형식의 regex
은 무엇입니까?
와 나는 형식 YYYY-MM-DD_hh:mm:ss
유효성 검사 날짜 - 콩 검증 주석 - 특정 형식
@Past //validates for a date that is present or past. But what are the formats it accepts
그게 불가능하면 날짜를 확인하고자, 나는 @Pattern
을 사용하고 싶습니다. 그러나 @Pattern
에서 위 형식의 regex
은 무엇입니까?
@Past
과 날짜를 시도하고 분석하는 것이 좋습니다에만 Date
및 Calendar
하지만 문자열을 지원하므로 날짜 형식의 어떤 개념이 없다.
@DateFormat
과 같은 사용자 정의 제약 조건을 만들 수
:
public class DateFormatValidatorForString
implements ConstraintValidator<DateFormat, String> {
private String format;
public void initialize(DateFormat constraintAnnotation) {
format = constraintAnnotation.value();
}
public boolean isValid(
String date,
ConstraintValidatorContext constraintValidatorContext) {
if (date == null) {
return true;
}
DateFormat dateFormat = new SimpleDateFormat(format);
dateFormat.setLenient(false);
try {
dateFormat.parse(date);
return true;
}
catch (ParseException e) {
return false;
}
}
}
SimpleDateFormat
인스턴스에 저장되지해야합니다 validator 클래스의 인스턴스 변수는 thread 세이프가 아니기 때문에 또는 병렬로 여러 스레드에서 안전하게 액세스 할 수있는 commons-lang 프로젝트의 FastDateFormat 클래스를 사용할 수 있습니다.
문자열에 대한 지원을 @Past
에 추가하려면 ConstraintValidator<Past, String>
을 구현하는 유효성 검사기를 구현하고 XML constraint mapping을 사용하여 등록 할 수 있습니다. 그러나 예상되는 형식을 지정하는 방법은 없습니다. 또는 @PastWithFormat
과 같은 다른 사용자 지정 제약 조건을 구현할 수도 있습니다.
컴파일 오류가 있습니다. 바운드 불일치 : DateFormat 유형이 ConstraintValidator 유형의 바운드 매개 변수 에 유효한 대용자가 아닙니다. – DEADEND
SimpleDateFormat의
boolean isValid(String date) {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'_'HH:mm:ss");
df.setLenient(false);
try {
df.parse(date);
} catch (ParseException e) {
return false;
}
return true;
}
스프링을 사용하는 경우'@ DateTimeFormat'을 사용할 수 있습니다. –