Custom Validator Annotation in Spring MVC

Viewed 457


I created a custom validation to <form:select> that populate country list.


Customer.jsp

    Country: 
    <form:select path="country" items="${countries}" />
    <form:errors path="country" cssClass="error"/>

FomeController.java

    @RequestMapping(value = "/customer", method = RequestMethod.POST)
    public String prosCustomer(Model model,
            @Valid @ModelAttribute("defaultcustomer") Customer customer,
            BindingResult result
    ) {
        CustomerValidator vali = new CustomerValidator();
        vali.validate(customer, result);
        if (result.hasErrors()) {
            return "form/customer";
        } else {
           ...
        }
    }

CustomValidator.java

public class CustomerValidator implements Validator {

    @Override
    public boolean supports(Class<?> type) {
        return Customer.class.equals(type);
    }

    @Override
    public void validate(Object target, Errors errors) {
        Customer customer = (Customer) target;
       int countyid=Integer.parseInt(customer.getCountry().getCountry());
        if (countyid==0) {
             errors.rejectValue("country",  "This value is cannot be empty");
        }
    }
}

Customer.java

   private Country country;

Validation is working perfectly fine. But the problem is that the validation method has attached another message too. validation view
Please tell me how to correct this message.

1 Answers

Can you try changing the implementation of Validator in controller as explained in https://stackoverflow.com/a/53371025/10232467

So you controller method can be like

@Autowired
CustomerValidator customerValidator;


@InitBinder("defaultcustomer")
protected void initDefaultCustomerBinder(WebDataBinder binder) {
binder.addValidators(customerValidator);
}

@PostMapping("/customer")
public String prosCustomer(@Validated Customer defaultcustomer, BindingResult bindingResult) {
// if error 
if (bindingResult.hasErrors()) {
    return "form/customer";
}
// if no error
return "redirect:/sucess";
}

Additionally the form model name in jsp should be defined as "defaultcustomer"

EDIT :

I missed the nested Country object in Customer class. In validator replace

errors.rejectValue("country",  "This value is cannot be empty");

with

errors.rejectValue("defaultcustomer.country",  "This value is cannot be empty");

Also found that Customer class should be modified as

@Valid
private Country country;
Related