Abhishek Singh
Abhishek Singh

Reputation: 10229

Spring MVC Validation not working

I am following this question ---> Spring MVC: How to perform validation?

Here is my controllers code

   @RequestMapping(value = "saveBankDetails.htm", method = RequestMethod.POST)
   public ModelAndView saveBankDetails(ModelMap model ,@Valid @ModelAttribute("SpringWeb")BankDetails bean, 
           BindingResult result){
               System.out.println(result.hasErrors());
               System.out.println(bean.getNoOfBankDetails());
               System.out.println(bean.getBankDetails().get(0).getNameOfBank());
                if(result.hasErrors())
                {
                    return new ModelAndView("error/error", "command",new String());
                }
                else{
                    return new ModelAndView("bankDetails/bankDetails", "command",bean);     
                }
   }

BankDetails bean contains ArrayList of EntityBankDetails. I have applied validation to a field of EntityBankDetail as shown

public class EntityBankDetail {
    @NotNull
    @Size(max = 3)
    private String nameOfBank;
    private Double EMIforProposedLoan;
    private String nameOfBranch;
    private String accountType;
    private String accountNumber;
    private String applicantType;
//Getters and Setters
    }

And i enter more than 3 characters in BankDetail field such that i get the output of controller on console as

false
3
fsdafsdfsdaf

Why is my validation not working? What is it that i am doing wrong ? Please Advice..

Edit to include BankDetailBean

/*
 * This class represent the entire Bank Details Page. It can contain 0-4 EntityBankDetais 
 * */
public class BankDetails {

    private ArrayList<EntityBankDetail> bankDetails;

    private String[] entities;
    @Size(max = 1)
    private int noOfBankDetails;

    public ArrayList<EntityBankDetail> getBankDetails() {
        return bankDetails;
    }
    public void setBankDetails(ArrayList<EntityBankDetail> bankDetails) {
        this.bankDetails = bankDetails;
    }
    public String[] getEntities() {
        return entities;
    }
    public void setEntities(String[] entities) {
        this.entities = entities;
    }
    public int getNoOfBankDetails() {
        return noOfBankDetails;
    }
    public void setNoOfBankDetails(int noOfBankDetails) {
        this.noOfBankDetails = noOfBankDetails;
    }
}

I get error on this bean that Class EntityBankDetail cannot be resolved to type. Both are in same package why so ??

Upvotes: 0

Views: 1552

Answers (1)

androberz
androberz

Reputation: 934

As you are using spring-mvc, you should specify <mvc:annotation-driven /> in your application context configuration to be able to use JSR-303 validation in your controllers. Or you can configure your instance of LocalValidatorFactoryBean and pass it inside <mvc:annotation-driven validator="yourValidator" />.

Upvotes: 1

Related Questions