Search code examples
validationspring-mvcpolymorphismhibernate-validator

hibernate validation - validate one of two paths


I use Spring MVC and Hibernate Validator. I have a OrderForm where you can choose from different payment methods. You have a radio button where you choose your payment method and enter the relevant parameters for the chosen payment methods.

Of course, if someone has chosen "Direct Debit" I don't want validation errors within the "PayPal" Form. At the time I do it like this:

public class OrderForm
{
   @NotNull
   private Integer customerId
   private PaymentMethodDebitForm paymentMethodDebitForm;
   private PaymentMethodPayPalForm paymentMethodPayPalForm;
   private String paymentSelection;

   @Valid
   public PaymentForm getPaymentForm ( )
   {
      if (paymentSelection.equals("PayPal"))
      {
         return paymentMethodPayPalForm;
      }
      return paymentMethodDebitForm;
    }

This way the validator gets only the form of the selected payment method.

I have two problems.

  1. Spring generates error codes for this with the name of the abstract superclass ("PaymentForm") and not the concret class ("PaymentMethodDebitForm"). As I use this form at a different place as the concrete subclass, I get two different codes resolved. I worked around this by setting the code in the forms:

    public class PaymentMethodDebitForm extends PaymentForm
    {
        @NotNull
        @Size(min = 3, max = 50, message = "{paymentMethodDebitForm.iban.Size}")
        private String iban;
    }
    
  2. In my jsp I need to refer to the concrete class when I render input field and refer to the super class when I render the error:

     <form:input path="paymentMethodDebitForm.iban" size="40" maxlength="50" />
     <form:errors path="paymentMethodForm.iban" />
    

    not so nice.

How do you handle polymorphic stuff when it comes to forms and validation with spring/hibernate? Is there some advice how to handle situations like this?


Solution

  • I think I would try to use validation groups via <f:validateBean validationGroups="..." /> or I would separate the forms. This is also discussed here - Validating different Validation Groups JSF 2.0