Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javax validation greater or less than from other property

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 ?

like image 304
Shahid Ghafoor Avatar asked May 24 '18 06:05

Shahid Ghafoor


People also ask

What does @NotNull annotation mean in bean property?

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.

What does javax validation constraints NotNull do?

@NotNull validates that the annotated property value is not null.

Is @valid and @validated the same?

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.

How does javax validation valid work?

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.


1 Answers

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.

like image 89
Mạnh Quyết Nguyễn Avatar answered Sep 19 '22 18:09

Mạnh Quyết Nguyễn