10

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 ?

Shahid Ghafoor
  • 3,329
  • 16
  • 62
  • 117

1 Answers1

4

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.

Mạnh Quyết Nguyễn
  • 16,814
  • 1
  • 21
  • 47