Randgalt / record-builder

Record builder generator for Java records
Apache License 2.0
758 stars 55 forks source link

Example of JSR303 validation for a MinMax record #46

Closed danp11 closed 3 years ago

danp11 commented 3 years ago

Hi,

With the JSR303 addition that you have now built in, could ou please provide an example of a MinMax(T min, T max) class that is possible to validate that min and max is notNull and also that min should be less or equal to max param?

Is this case possible in the todays master?

/Dan

Randgalt commented 3 years ago

You have to write custom validators for that stuff. You should SO for how to custom validations in Java. I don't have any examples of that at hand.

Randgalt commented 3 years ago

Here's an example I found: https://www.logicbig.com/tutorials/java-ee-tutorial/jax-rs/custom-entity-validation.html

danp11 commented 3 years ago

Thanks Jordan.

Found that one can also use @AssertTrue directly in the record body.


@RecordBuilder.Options(useValidationApi = true)
@RecordBuilder
public record MinMax<T extends Comparable<T>>(@NotNull T min, @NotNull T max) {

    @AssertTrue
    private boolean isMaxLargerOrEqualToMin() {
        return min != null && max != null && max.compareTo(min) >= 0;
    }
}