yavi icon indicating copy to clipboard operation
yavi copied to clipboard

Overriding constraints

Open vineethgeorge03 opened this issue 3 years ago • 4 comments

Hello, Thank you very much for this library. I have a query: Suppose I have a base validator

ValidatorBuilder<Car> baseValidatorBuilder = ValidatorBuilder.<Car>of()
            .constraint(Car::getManufacturer, "manufacturer", c -> c.notNull())
            .constraint(Car::getSeatCount, "seatCount", c -> c.greaterThanOrEqual(2))

Is it currently possible to reuse the above constraints and override one of the constraints like this

Validator<Car> validator = baseValidatorBuilder.constraint(Car::getManufacturer, "manufacturer", c -> c.isNull())
                .build();

I am asking this because i have a use case where depending on a condition, the constraints conditions keep changing. Currently I am rewriting the entire validator depending on the condition

vineethgeorge03 avatar May 24 '22 14:05 vineethgeorge03

There is a way to add constraints as follows

ValidatorBuilder<Car> baseValidatorBuilder = ValidatorBuilder.<Car>of()
            .constraint(Car::getSeatCount, "seatCount", c -> c.greaterThanOrEqual(2))

Validator<Car> validator1 = new ValidatorBuilder(baseValidatorBuilder)
                .constraint(Car::getManufacturer, "manufacturer", c -> c. notNull())
                .build();

Validator<Car> validator2 = new ValidatorBuilder(baseValidatorBuilder)
                .constraint(Car::getManufacturer, "manufacturer", c -> c.isNull())
                .build();

But overriding was not considered. Not sure it works

making avatar May 26 '22 11:05 making

understood . thank you

vineethgeorge03 avatar May 26 '22 12:05 vineethgeorge03

Is it a feature request?

making avatar May 26 '22 12:05 making

yes .. was thinking if we can support it by overridding using keys or set a priority to the key .. For ex in the code below the key manufacturer is repeated , so it will override the first constraint .

ValidatorBuilder<Car> baseValidatorBuilder = ValidatorBuilder.<Car>of()
            .constraint(Car::getManufacturer, "manufacturer", c -> c.notNull())
            .constraint(Car::getSeatCount, "seatCount", c -> c.greaterThanOrEqual(2))
Validator<Car> validator = baseValidatorBuilder.constraint(Car::getManufacturer, "manufacturer", c -> c.isNull())
                .build();

vineethgeorge03 avatar May 26 '22 16:05 vineethgeorge03

@vineethgeorge03 FYI, this is (finally) supported in YAVI 0.13.0. You can override constraints as follows

Validator<Car> validator = baseValidatorBuilder.constraint(Car::getManufacturer, "manufacturer", c -> c.isNull())
                .conflictStrategy(ConflictStrategy.OVERRIDE)
                .build();

making avatar May 16 '23 08:05 making

well done! nice feature!

ffroliva avatar May 16 '23 20:05 ffroliva

thanks a lot !!!

vineethgeorge03 avatar Jun 09 '23 13:06 vineethgeorge03