Cross-field validation using Bean Validation (JSR 303)

I recently introduced the use of Bean Validation in one of the project I was working on. At the very start, it was just a complete experiment with a very “defensive” implementation, with the mindset that if the use of this API proved to be problematic, it would be thrown away.

Turned out to be a very good set of API, and it is very enjoyable to use.

It is true that there are things to read, learn and experiment (here, unit testing helps A LOT) and the site from JBoss helped a lot.

Amongst the many things I learnt, one of the immediate requirement I encountered was the ability to implement a cross-field validation. I suppose it is understandable as to why the cross-field validation is not part of the standard API. Why how would one standardise such case with so many variations/approaches, etc. I am sure though that the JSR team will eventually address it.

That being said, Bean Validation allows flexibility via the use of Custom Validator and with that, cross-field validation can be implemented. The example that I used in this entry today is based on the post in stackoverflow.com by user Nicko (Nicko 2010).

Supposed there is an entity called Purchase. A Purchase must be allocated to correct authorisation department, and also payment department. For a Purchase to be considered valid, it must also be authorised by a person from that authorisation department, and paid by someone from the payment department. (This might be a silly example, but you’ll get the intention)..

Using the example from stackoverflow.com, the classes are:

EnrolmentValid

package com.wordpress.dwuysan;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import javax.validation.Constraint;
import javax.validation.Payload;

/**
 * @author dwuysan
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = EnrolmentValidator.class)
public @interface EnrolmentValid {

    String message() default "{com.wordpress.dwuysan.EnrolmentValid.message}";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

    String personNoFieldName();

    String departmentNoFieldName();

    @Target({ElementType.TYPE, ElementType.ANNOTATION_TYPE})
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    @interface List {
        EnrolmentValid[] value();
    }
}

EnrolmentValidator

package com.wordpress.dwuysan;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

import org.apache.commons.beanutils.BeanUtils;

/**
 * @author dwuysan
 */
public class EnrolmentValidator 
        implements ConstraintValidator<EnrolmentValid, Object> {

    private String personNoFieldName;
    private String departmentNoFieldName;

    @Override
    public void initialize(final EnrolmentValid a) {
        this.personNoFieldName = a.personNoFieldName();
        this.departmentNoFieldName = a.departmentNoFieldName();
    }

    @Override
    public boolean isValid(
                final Object t, final ConstraintValidatorContext cvc) {
        final Object personNo;
        final Object departmentNo;
        try {
            personNo = BeanUtils.getProperty(t, 
                this.personNoFieldName);
            departmentNo = BeanUtils.getProperty(t,
                this.departmentNoFieldName);
            /* Validation logic goes here */
        } catch (final Exception e) {
            throw new RuntimeException(e.getMessage(), e);
        }

        if (personNo == null || departmentNo == null) { return true; }

        // return false, just to make it always fail
        return false;
    }
}

Purchase

package com.wordpress.dwuysan;

import javax.validation.constraints.NotNull;

/**
 * @author dwuysan
 */
@EnrolmentValid.List(value = {
    @EnrolmentValid(
        personNoFieldName = "authorisePersonNo", 
        departmentNoFieldName = "authorisationDepartmentNo", 
        message="Authoriser does not belong to the auth department"),
    @EnrolmentValid(
        personNoFieldName = "payerPersonNo", 
        departmentNoFieldName = "paymentDepartmentNo", 
        message="Payer does not belong to the payment department")
})
public class Purchase {

    private Integer authorisePersonNo;
    private Integer payerPersonNo;

    @NotNull
    private Integer authorisationDepartmentNo;
    
    @NotNull
    private Integer paymentDepartmentNo;
    
    /* accessor/mutator methods not shown */
}

Have tried this approach and it worked perfectly. However, if then we were to refactor the fields, say in this case the names of the properties are too long and it should be changed to authPersNo and , then this example would fail (again, of course JUnit will pick this up).

ALTERNATIVE APPROACH

The other option is to actually remove the use of “reflection”, and instead, use an additional class just exposing those fields to be validated.

EnrolmentValidation

package com.wordpress.dwuysan;

/**
 * @author dwuysan
 */
public final class EnrolmentValidation {
    private final Integer personNo;
    private final Integer departmentNo;

    public EnrolmentValidation(
            final Integer personNo, 
            final Integer departmentNo) {
        this.personNo = personNo;
        this.departmentNo = departmentNo;
    }

    public Integer getDepartmentNo() {
        return departmentNo;
    }

    public Integer getPersonNo() {
        return personNo;
    }
}

Then change the Validator to directly access the fields (instead of using reflection).

EnrolmentValidator

package com.wordpress.dwuysan;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * @author dwuysan
 */
public class EnrolmentValidator 
        implements ConstraintValidator<EnrolmentValid, EnrolmentValidation> {

    @Override
    public void initialize(final EnrolmentValid a) {}
    
    @Override
    public boolean isValid(
                final EnrolmentValidation t, 
                final ConstraintValidatorContext cvc) {
        if (t.getPersonNo() == null || t.getDepartmentNo() == null) {
            return true;
        }
        /* Validation logic goes here */

        // return false, just to make it always fail
        return false;
    }
}

Also, change the annotation by removing the field names.

EnrolmentValid

package com.wordpress.dwuysan;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import javax.validation.Constraint;
import javax.validation.Payload;

/**
 * @author dwuysan
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = EnrolmentValidator.class)
public @interface EnrolmentValid {

    String message() default "{com.wordpress.dwuysan.EnrolmentValid.message}";

    Class[] groups() default {};

    Class[] payload() default {};

    // String personNoFieldName();

    // String departmentNoFieldName();

    @Target({ElementType.TYPE, ElementType.ANNOTATION_TYPE})
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    @interface List {
        EnrolmentValid[] value();
    }
}

THEN, the problematic one is the Purchase class itself. For a start, we could simply add methods returning EnrolmentValidation object, with the method annotated with @EnrolmentValid

Purchase

package com.wordpress.dwuysan;

import javax.validation.constraints.NotNull;

/**
 * @author dwuysan
 */
public class Purchase {

    private Integer authorisePersonNo;
    private Integer payerPersonNo;

    @NotNull
    private Integer authorisationDepartmentNo;
    
    @NotNull
    private Integer paymentDepartmentNo;

    @EnrolmentValid
    public EnrolmentValidation getAuthPersonDepartmentEnrolmentValidation() {
        return new EnrolmentValidation(
            this.authorisePersonNo, 
            this.authorisationDepartmentNo);
    }

    @EnrolmentValid
    public EnrolmentValidation getPayerDepartmentEnrolmentValidation() {
        return new EnrolmentValidation(
            this.payerPersonNo,
            this.paymentDepartmentNo);
    }

    /* accessor/mutator methods not shown */
}

That works as expected. However, it may not be the most ideal scenario since the class Purchase is now “polluted” with validation specific methods. Also, some prefer clear separation between the domain model and its validation. One way to achieve this is to use interface (and an Adapter class).

Please refer to the following interface.

PurchaseValidation

package com.wordpress.dwuysan;

import javax.validation.constraints.NotNull;

/**
 * @author dwuysan
 */
public interface PurchaseValidation {

    @NotNull
    Integer getPayerPersonNo();

    @NotNull
    Integer getPaymentDepartmentNo();

    @NotNull
    Integer getAuthorisePersonNo();

    @NotNull
    Integer getAuthorisationDepartmentNo();

    @EnrolmentValid
    EnrolmentValidation getAuthPersonDepartmentEnrolmentValidation();

    @EnrolmentValid
    EnrolmentValidation getPayerDepartmentEnrolmentValidation();
}

I supposed the way to look at it is to say, “Here is the list of validations relating to Purchase“. And so that the class Purchase is not tainted with validation logic, create a simple Adapter class as follows.

PurchaseValidationAdapter

package com.wordpress.dwuysan;

/**
 * @author dwuysan
 */
public class PurchaseValidationAdapter implements PurchaseValidation {
    private final Purchase purchase;

    public PurchaseValidationAdapter(Purchase purchase) {
        this.purchase = purchase;
    }

    @Override
    public Integer getPayerPersonNo() {
        return this.purchase.getPayerPersonNo();
    }

    @Override
    public Integer getPaymentDepartmentNo() {
        return this.purchase.getPaymentDepartmentNo();
    }

    @Override
    public Integer getAuthorisePersonNo() {
        return this.purchase.getAuthorisePersonNo();
    }

    @Override
    public Integer getAuthorisationDepartmentNo() {
        return this.purchase.getAuthorisationDepartmentNo();
    }

    @Override
    public EnrolmentValidation getAuthPersonDepartmentEnrolmentValidation() {
        return new EnrolmentValidation(
                this.purchase.getAuthorisePersonNo(),
                this.purchase.getAuthorisationDepartmentNo());
    }

    @Override
    public EnrolmentValidation getPayerDepartmentEnrolmentValidation() {
        return new EnrolmentValidation(
                this.purchase.getPayerPersonNo(),
                this.purchase.getPaymentDepartmentNo());
    }
}

CONSIDERATIONS

I suppose the alternative approach presented here removes the use of “reflection”, and at the same time introduces the separation between the validation layer and the actual business domain model. Using Adapter, we can also adapt other models into a single validation layer. For example, when dealing with a legacy code, an application may have multiple class representing the very same business object. In this case, perhaps consider a class like PurchaseSummary, PurchaseLite, etc. This alternative approach, however, does introduce more code.

I am sure that people who have used JSR-303 have also encountered the need of cross-field validation. I am interested to know their thoughts and any comment to this post is very welcomed.

References:
Nicko, 2010, Cross field validation with Hibernate Validator (JSR 303), accessed 20 March 2012.

Advertisements