with respect to javax.validation
@NotNull(message = "From can't be null")
@Min(value = 1, message = "From must be greater than zero")
private Long from;
@NotNull(message = "To can't be null")
@Min(value = 1, message = "To must be greater than zero")
private Long to;
I want to also validate that FROM should be less than TO and TO should be greater than FROM ? how we can do this using javax validation's annotation ?
The @NotNull annotation is, actually, an explicit contract declaring that: A method should not return null. Variables (fields, local variables, and parameters) cannot hold a null value.
@NotNull validates that the annotated property value is not null.
The @Valid annotation ensures the validation of the whole object. Importantly, it performs the validation of the whole object graph. However, this creates issues for scenarios needing only partial validation. On the other hand, we can use @Validated for group validation, including the above partial validation.
validation will validate the nested object for constraints with the help of javax. validation implementation provider, for example, hibernate validator. @Valid also works for collection-typed fields. In the case of collection-typed fields, each collection element will be validated.
You need a custom cross field validation
annotation.
One way is to annotate your custom class with @YourCustomAnnotation
.
In YourCustomAnnotationValidator
you have access to your value, hence you can implement your logic there:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Constraint(validatedBy = DateValidator.class)
public @interface RangeCheck {
String message();
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
public class RangeCheckValidtor implements ConstraintValidator<RangeCheck, YourDto> {
@Override
public void initialize(RangeCheck date) {
// Nothing here
}
@Override
public boolean isValid(YourDto dto, ConstraintValidatorContext constraintValidatorContext) {
if (dto.getFrom() == null || dto.getTo() == null) {
return true;
}
return from < to;
}
}
Then mark your YourDto
class with @RangeCheck
:
@RangeCheck(message = "your messgae")
public class YourDto {
// from
// to
}
Or simply manually validate the relation of two fields.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With