In this chapter, we will rewrite the previous example. The model car “Car” is enriched with a few additional annotations. @Min – Specifies the minimum length of text string entered into this field. @Size lets you specify its length from-to. In both cases, the “message” parameter specifies the message that will be displayed on the form if the field validation fails. If you do not specify a custom message, the default template from Spring will be displayed.

The method that handles the POST request on the controller is supplemented with the @Valid annotation and an additional parameter. @Valid means that the “car” object will only be sent from the form after successful data validation. The BindingResult class object allows us to pull out specific errors

which appear. I do not use his ability here.

Let’s go to the JSP file of the form:

The new thing that comes up here is the tag:

<form: errors path = “brand” />

It specifies that any errors related to the field should be displayed here – and for each field :)

Other examples of validation annotations:

@Max – specifies the maximum string length

@NotNull – Specifies that the field cannot remain blank

@Pattern – allows you to validate using regular expressions

@NotEmpty – not empty string (with hibernate)