Bean Validation - Sign Up

Sign Up

Add Hibernate Validator dependency to pom.xml.

<!-- -->

Bean validation need <mvc:annotation-driven /> in spring-bbs-servlet.xml.

Declare constraints rules on the User class that is bound to the sign-up form.
import javax.validation.constraints.Email;
import javax.validation.constraints.Size;

@Size(min=5, message="It is not an email.")
@Email(message="It is not an email.")
private String email;

@Size(min=4, message="Your password must be at least 4 characters long.")
private String passwd;

@Size(min=2, message="The full name must exceed two characters.")
private String name;

@Size(min=6, max=20, message="It is not a mobile phone number.")
private String mobile;

The sign-up form handler must create an empty object with no content and pass it to the view. Creating an empty object and giving it to the view is a spec and should be followed.
@RequestMapping(value="/signUp", method=RequestMethod.GET)
public String signUp(Model model) {
  model.addAttribute("user", new User());
  return "users/signUp";

The subscription handler must have a parameter of type BindingResult after the @Valid annotated parameter. Otherwise, an HTTP 400 error will occur.
import javax.validation.Valid;
import org.springframework.validation.BindingResult;

@RequestMapping(value="/signUp", method=RequestMethod.POST)
public String signUp(@Valid User user, BindingResult bindingResult) {
  //A bean that fails validation is stored in the BindingResult and the BindingResult is passed to the view.
  if (bindingResult.hasErrors()) {
    return "users/signUp";

Modify signUp.jsp as shown below.(<sf:errors > is a Spring's form tag that displays validation errors to the user)

<%@ taglib uri="" prefix="sf" %>

<sf:form id="signUpForm" action="signUp" method="post" modelAttribute="user"
      onsubmit="return check();">
<sf:errors path="*" cssClass="error" />
  <td style="width: 200px;">Full Name</td>
  <td style="width: 390px">
    <sf:input path="name" /><br />
    <sf:errors path="name" cssClass="error" />
    <sf:password path="passwd" /><br />
    <sf:errors path="passwd" cssClass="error" />
  <td colspan="2" style="text-align: center;font-weight: bold;">
    Do not input email account password!
  <td><input type="password" name="confirm" /></td>
    <sf:input path="email" /><br />
    <sf:errors path="email" cssClass="error" />
    <sf:input path="mobile" /><br />
    <sf:errors path="mobile" cssClass="error" />
<div style="text-align: center;padding-bottom: 15px;">
  <input type="submit" value="Submit" />

Add the following to the stylesheet.

.error {
  color: red;

Test Screen

Sign Up

Bean validaion failed