Nicola Tesser
Nicola Tesser

Reputation: 11

Bean Validation using complex business logic and remote service calls

I am implementing for a web application an input validation which is fairly complex and should take in input an ID and will call several other systems in order to check whether this ID is a valid on or not before persisting an object containing this id. I was thinking to use bean validation, but then I found myself creating a bean specifically for allowing this validation to take place. In fact I need to give my validator not only the ID but also some context information in order to make my remote service calls.

Do you think bean-validation is always the right place to put validation, even if it's complex and requires context outside the scope of the Bean to validate?

Would be a Spring service which implement the business logic validation rules a better choice?

Or maybe other validators (Hibernate, Spring) could deal with my use case better?

What are best practices around complex validation with Bean validation?

Upvotes: 0

Views: 1565

Answers (2)

michaldo
michaldo

Reputation: 4599

Bean validation applies best to check user input from web form is correct.

If you must verify user input in other systems, you should implement it as regular step in your algorithm.

Update

Bean validation is invented to replace trivial, boring manual validation like if x != null && x < 0 then doReject() with elegant short annotation like @Min(1)

If your id verification is not trivial then I recommend to implement it as clearly visible operation in your algorithm. It is easier to implement and easier to maintain than hide details within custom beans validation.

However, if your validation is common in your application, like French zip validation described in different answer, it could be good idea to implement custom bean validation and reuse it in many places.

Upvotes: 2

LHA
LHA

Reputation: 9655

The answer is Yes. You can develop CDI Service Bean (@ApplicationScoped for example) and Inject this CDI bean into ConstraintValidator class.

You can see an example in Java bean validation spec page: http://beanvalidation.org/1.1/changes/

class ZipCodeValidator implements ConstraintValidator<ZipCode, String> {

@Inject
private ZipService service;

public void initialize(ZipCode zipCode) {}

public boolean isValid(String value, ConstraintValidationContext context) {
    if (value==null) return true;
    return service.isZipCodeValid(value);
}
}

Upvotes: 1

Related Questions