Question

I'm applying hibernate validation on some of my objects. I want to validate several different classes one after the other, but break the validation on the first error and skip the rest.

How could I write this apart from always having to check if the error size i >0 after each validation?

class Person, Car, House;


Validator validator = Validation.buildDefaultValidatorFactory().getValidator();

error = validator.validate(myPerson);
if (error.size() > 0) return error;

error = validator.validate(myCar, SpecificContraint.class);
if (error.size() > 0) return error;

error = validator.validate(myHouse);
if (error.size() > 0) return error;

//repeat N times
Was it helpful?

Solution

Part of the specification is to check the full validation scope for errors. Basically, you want to respond with as many errors as possible to the user, so he can fix them all in one go, rather than having to go through multiple.

If you particularly want to do as you say, your code seems fine to me, except I would probably use

if (!error.isEmpty()) return error;

instead.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top