Simple validations on the bean

The Bean Validation API specifies a number of validations that can be specified on attributes on the beans. Take a look at the following listing:

   @Size(min = 6, message = "Enter at least 6 characters") 
private String name;
@Size(min = 6, message = "Enter at least 6 characters")
private String userId;
@Size(min = 8, message = "Enter at least 8 characters")
private String password;
@Size(min = 8, message = "Enter at least 8 characters")
private String password2;

An important thing to note are as follows:

  • @Size(min = 6, message = "Enter at least 6 characters") : This specifies that the field should at least have six characters. If the validation does not pass, the text from the message attribute is used as a validation error message.

Other validations that can be performed using Bean Validation are as follows:

  • @NotNull: It should not be null
  • @Size(min =5, max = 50): Maximum size of 50 characters and minimum of 5 characters.
  • @Past: Should be a date in the past
  • @Future: Should be a future date
  • @Pattern: Should match the provided regular expression
  • @Max: Maximum value for the field
  • @Min: Minimum value for the field

Now let's focus on getting the controller method to validate the form on submits. The complete method listing is as follows:

    @RequestMapping(value = "/create-user-with-validation",  
method = RequestMethod.POST)
public String addTodo(@Valid User user, BindingResult result) {
if (result.hasErrors()) {
return "user";
}
logger.info("user details " + user);
return "redirect:list-users";
}

Some important things are as follows:

  • public String addTodo(@Valid User user, BindingResult result): When the @Valid annotation is used, Spring MVC validates the bean. The result of the validation is made available in the BindingResult instance result.
  • if (result.hasErrors()): Checks whether there are any validation errors.
  • return "user": If there are validation errors, we send the user back to the user page.

We need to enhance the user.jsp to show the validation messages in case of validation errors. The complete list for one of the fields is shown here. Other fields have to be similarly updated:

    <fieldset> 
<form:label path="name">Name</form:label>
<form:input path="name" type="text" required="required" />
<form:errors path="name" cssClass="text-warning"/>
</fieldset>

<form:errors path="name" cssClass="text-warning"/>: This is the Spring form tag to display the errors related to the field name specified in the path. We can also assign the CSS class used to display the validation error.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset