I want to validate a date in Long
type to be greater than the current time.
I've seen @Past
, @Future
and so on... but It is not applicable to Long
data type.
I'm looking for something like this:
@FutureOrPresent
private Long dateStart;
@Future
private Long dateEnd;
But working for Long
values.
How can I validate date > System.currentTimeMillis()
?
Thanks in advance.
In case you want to use existing constraint annotations but the types (Long in your case) on which you want to apply them are not supported you need to:
Create your own implementation of ConstraintValidator, for example:
public class FutureLongValidator implements ConstraintValidator<Future, Long> {
public boolean isValid(Long value, ConstraintValidatorContext context) {
if ( value == null ) {
return true;
}
return value > System.currentTimeMillis();
}
}
Then register it so that HV knows about it and can use it for validation. There are a few ways how this can be done. I'd suggest using the ServiceLoader approach. To do that a file META-INF/services/javax.validation.ConstraintValidator
must be created and the fully qualified name of the validator added to it:
some.package.FutureLongValidator
some.package.FutureOrPresentLongValidator
for a more detailed instructions and a sample project check out this post that covers the topic in details - Adding custom constraint definitions via the Java service loader