2

I have a bean with flowing structure

public class Payment {
private String payType;
@Valid
private CreditCard creditCard;
private BankAccount bankAccount;
}

The credidCard class

public class CreditCard {
@Pattern(regexp="(\\d{16})")
private String cardNumber;
@NotEmpty
@Size(max=40)
private String name;
@NotEmpty
private String securityCode;
@Future
private Date expiration_Date;
}

Like that The validation applied to Bank account class also. Now What I want is If PayType is Credit then I need to validate CreditCard other wise I need to validate the BankAccount. I know for this type we can write a custom validater like in the link JSR 303 Validation

But in this case I need to write validation logic for all the field of the class. Can write some logic so that according paytype existing validation will work. That Just I want the @Valid annotation according type. Please Help me

Krushna
  • 5,059
  • 5
  • 32
  • 49

1 Answers1

0

I finally got the solutions for the problem and I am posting the answer so that It will be help full to other. The logic is I need to provide a custom method which will return the object which I want to validate. Like below

public class Payment {
private String payType;

private CreditCard creditCard;
private BankAccount bankAccount;

@Valid
public Object getValid(){
    if(creditCard!=null && payType.equals("credit"))
        return creditCard;
    if(bankAccount !=null&& payType.equals("bank")){
        return bankAccount;
    }
    return null;
}  
}
Krushna
  • 5,059
  • 5
  • 32
  • 49