Created
December 1, 2014 17:21
-
-
Save sruehl/0a846ab61e8698107977 to your computer and use it in GitHub Desktop.
LocalDateValidator JSR-303
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package training.domain; | |
import javax.validation.Constraint; | |
import javax.validation.Payload; | |
import java.lang.annotation.Documented; | |
import java.lang.annotation.ElementType; | |
import java.lang.annotation.Retention; | |
import java.lang.annotation.RetentionPolicy; | |
import java.lang.annotation.Target; | |
import java.time.temporal.ChronoUnit; | |
import java.util.concurrent.TimeUnit; | |
/** | |
* @author sruehl | |
* @version $LastChangedVersion$ | |
*/ | |
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE}) | |
@Retention(RetentionPolicy.RUNTIME) | |
@Constraint(validatedBy = LocalDateValidator.class) | |
@Documented | |
public @interface CheckLocalDate { | |
public static enum Direction { | |
AFTER, BEFORE | |
} | |
String message() default "{training.domain.localDate}"; | |
Class<?>[] groups() default {}; | |
Class<? extends Payload>[] payload() default {}; | |
Direction direction(); | |
ChronoUnit timeUnit(); | |
long units(); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package training.domain; | |
import javax.validation.ConstraintValidator; | |
import javax.validation.ConstraintValidatorContext; | |
import java.time.LocalDate; | |
import java.time.chrono.ChronoLocalDate; | |
import java.time.temporal.ChronoUnit; | |
/** | |
* @author sruehl | |
* @version $LastChangedVersion$ | |
*/ | |
public class LocalDateValidator implements ConstraintValidator<CheckLocalDate, LocalDate> { | |
private CheckLocalDate.Direction direction; | |
private ChronoLocalDate chronoLocalDate; | |
public void initialize(CheckLocalDate constraintAnnotation) { | |
direction = constraintAnnotation.direction(); | |
final long d = constraintAnnotation.units(); | |
final ChronoUnit unit = constraintAnnotation.timeUnit(); | |
chronoLocalDate = LocalDate.now().minus(d, unit); | |
} | |
public boolean isValid(LocalDate dateToCheck, ConstraintValidatorContext constraintContext) { | |
if (dateToCheck == null) { | |
return true; | |
} | |
switch (direction) { | |
case AFTER: | |
return dateToCheck.isBefore(chronoLocalDate); | |
case BEFORE: | |
return dateToCheck.isAfter(chronoLocalDate); | |
} | |
throw new IllegalStateException("Unreachable code"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment