HTML5 Validation Dialect - Usage

Spring users

  1. Configure JSR-303 annotations in your form bean

    class UserFormBean {
    @Email
    @NotEmpty
    private String username;
    @Size(min = 5, max = 10)
    private String code;
    @Min(value = 18)
    @Max(value = 100)
    @NotNull
    private Integer age;
    @Range(min = 0, max = 10)
    private Integer highSchoolMark;
    @URL(regexp = URLPerformer.URL_REGEXP)
    private String personalWebPage;
    @URL(protocol = "http", host = "localhost", port = 8080)
    private String applicationWebPage;
    ...
    }
  2. Add a instance of the form bean to your model in your controller

    @RequestMapping("/userCreate.html")
    public String userCreate(Model model) {
    model.addAttribute("userFormBean", new UserFormBean());
    return "userCreate.html";
    }
    view raw edit.java hosted with ❤ by GitHub
  3. Use val:validate in your HTML form

    <form action="userSave.do" val:validate="${userFormBean}" method="post">
    <p>
    <label for="username">E-mail</label>
    <input type="text" name="username" id="username" />
    </p>
    <p>
    <label for="code">Code</label>
    <input type="text" name="code" id="code" />
    </p>
    <p>
    <label for="age">Age</label>
    <input type="text" name="age" id="age" />
    </p>
    <p>
    <label for="highSchoolMark">Mark</label>
    <input type="text" name="highSchoolMark" id="highSchoolMark" />
    </p>
    <p>
    <label for="personalWebPage">Personal Web Page</label>
    <input type="text" name="personalWebPage" id="personalWebPage" />
    </p>
    <p>
    <label for="applicationWebPage">Demo application Web Page</label>
    <input type="text" name="applicationWebPage" id="applicationWebPage" />
    </p>
    <input type="submit" />
    </form>
    view raw userForm.html hosted with ❤ by GitHub
  4. Use @Valid annotation in your controller

    @RequestMapping(value = "/userSave.do", method = RequestMethod.POST)
    public String userSave(@Valid UserFormBean userForm) {
    userDAO.save(userForm.buildUser());
    return "redirect:/userList.html";
    }
    view raw userSave.java hosted with ❤ by GitHub

In order to make the example simpler, th:field is not used, but you usually would combine val:validate with th:object and th:errors.

You could also download the example webapp or browse its source code.



Back to home page