2.3.2 Performing validation at form binding
Now that you’ve declared how a Taco and TacoOrder should be validated, we need to revisit each of the controllers, specifying that validation should be performed when the forms are POSTed to their respective handler methods.
To validate a submitted Taco, you need to add the JavaBean Validation API’s @Valid annotation to the Taco argument of the DesignTacoController’s processTaco() method, as shown next.
Listing 2.13 Validating a POSTed Taco
import javax.validation.Valid;
import org.springframework.validation.Errors;
...
@PostMapping
public String processTaco(@Valid @ModelAttribute("taco") Taco taco, Errors errors) {
if (errors.hasErrors()) {
return "design";
}
// Save the taco...
// We'll do this in chapter 3
log.info("Processing taco: " + taco);
return "redirect:/orders/current";
}The @Valid annotation tells Spring MVC to perform validation on the submitted Taco object after it’s bound to the submitted form data and before the processTaco() method is called. If there are any validation errors, the details of those errors will be captured in an Errors object that’s passed into processTaco(). The first few lines of processTaco() consult the Errors object, asking its hasErrors() method if there are any validation errors. If there are, the method concludes without processing the Taco and returns the "design" view name so that the form is redisplayed.
To perform validation on submitted TacoOrder objects, similar changes are also required in the processOrder() method of OrderController, as shown in the next code listing.
Listing 2.14 Validating a POSTed TacoOrder
@PostMapping
public String processOrder(@Valid TacoOrder order, Errors errors) {
if (errors.hasErrors()) {
return "orderForm";
}
log.info("Order submitted: " + order);
return "redirect:/";
}In both cases, the method will be allowed to process the submitted data if there are no validation errors. If there are validation errors, the request will be forwarded to the form view to give the user a chance to correct their mistakes.
But how will the user know what mistakes require correction? Unless you call out the errors on the form, the user will be left guessing about how to successfully submit the form.
