Form Validation with AngularJS and Spring MVC – 用AngularJS和Spring MVC进行表单验证

最后修改: 2017年 3月 22日


1. Overview


Validation is never quite as straightforward as we expect. And of course validating the values entered by a user into an application is very important for preserving the integrity of our data.


In the context of a web application, data input is usually done using HTML forms and requires both client-side and server-side validation.


In this tutorial, we’ll have a look at implementing client-side validation of form input using AngularJS and server-side validation using the Spring MVC framework.

在本教程中,我们将看看使用AngularJS实现表单输入的客户端验证和使用Spring MVC框架实现服务器端验证

This article focuses on Spring MVC. Our article Validation in Spring Boot describes how to do validations in Spring Boot.

本文主要介绍Spring MVC。我们的文章Spring Boot中的验证介绍了如何在Spring Boot中进行验证。

2. Maven Dependencies


To start off, let’s add the following dependencies:



The latest versions of spring-webmvc, hibernate-validator and jackson-databind can be downloaded from Maven Central.


3. Validation Using Spring MVC

3.使用Spring MVC进行验证

An application should never rely solely on client-side validation, as this can be easily circumvented. To prevent incorrect or malicious values from being saved or causing improper execution of the application logic, it is important to validate input values on the server side as well.


Spring MVC offers support for server-side validation by using JSR 349 Bean Validation specification annotations. For this example, we will use the reference implementation of the specification, which is hibernate-validator.

Spring MVC通过使用JSR 349 Bean Validation规范注解,为服务器端验证提供了支持。在这个例子中,我们将使用该规范的参考实现,也就是hibernate-validator

3.1. The Data Model


Let’s create a User class that has properties annotated with appropriate validation annotations:


public class User {

    private String email;

    @Size(min = 4, max = 15)
    private String password;

    private String name;

    @Digits(integer = 2, fraction = 0)
    private int age;

    // standard constructor, getters, setters

The annotations used above belong to the JSR 349 specification, with the exception of @Email and @NotBlank, which are specific to the hibernate-validator library.

上面使用的注解属于JSR 349规范,但@Email@NotBlank除外,它们是hibernate-validator库特有的。

3.2. Spring MVC Controller

3.2.Spring MVC控制器

Let’s create a controller class that defines a /user endpoint, which will be used to save a new User object to a List.


In order to enable validation of the User object received through request parameters, the declaration must be preceded by the @Valid annotation, and the validation errors will be held in a BindingResult instance.


To determine if the object contains invalid values, we can use the hasErrors() method of BindingResult.


If hasErrors() returns true, we can return a JSON array containing the error messages associated with the validations that did not pass. Otherwise, we will add the object to the list:


@PostMapping(value = "/user")
public ResponseEntity<Object> saveUser(@Valid User user, 
  BindingResult result, Model model) {
    if (result.hasErrors()) {
        List<String> errors = result.getAllErrors().stream()
        return new ResponseEntity<>(errors, HttpStatus.OK);
    } else {
        if ( -> user.getEmail().equals(it.getEmail()))) {
            return new ResponseEntity<>(
              Collections.singletonList("Email already exists!"), 
        } else {
            return new ResponseEntity<>(HttpStatus.CREATED);

As you can see, server-side validation adds the advantage of having the ability to perform additional checks that are not possible on the client side.


In our case, we can verify whether a user with the same email already exists – and return a status of 409 CONFLICT if that’s the case.

在我们的案例中,我们可以验证是否已经存在一个具有相同电子邮件的用户–如果是这样的话,则返回409 CONFLICT状态。

We also need to define our list of users and initialize it with a few values:


private List<User> users = Arrays.asList(
  new User("", "pass", "Ana", 20),
  new User("", "pass", "Bob", 30),
  new User("", "pass", "John", 40),
  new User("", "pass", "Mary", 30));

Let’s also add a mapping for retrieving the list of users as a JSON object:


@GetMapping(value = "/users")
public List<User> getUsers() {
    return users;

The final item we need in our Spring MVC controller is a mapping to return the main page of our application:

我们在Spring MVC控制器中需要的最后一项是一个映射,用来返回我们应用程序的主页面。

public String getUserProfilePage() {
    return "user";

We will take a look at the user.html page in more detail in the AngularJS section.

我们将在AngularJS部分更详细地查看 user.html页面。

3.3. Spring MVC Configuration

3.3.Spring MVC配置

Let’s add a basic MVC configuration to our application:


@ComponentScan(basePackages = "com.baeldung.springmvcforms")
class ApplicationConfiguration implements WebMvcConfigurer {

    public void configureDefaultServletHandling(
      DefaultServletHandlerConfigurer configurer) {

    public InternalResourceViewResolver htmlViewResolver() {
        InternalResourceViewResolver bean = new InternalResourceViewResolver();
        return bean;

3.4. Initializing the Application


Let’s create a class that implements WebApplicationInitializer interface to run our application:


public class WebInitializer implements WebApplicationInitializer {

    public void onStartup(ServletContext container) throws ServletException {

        AnnotationConfigWebApplicationContext ctx
          = new AnnotationConfigWebApplicationContext();
        container.addListener(new ContextLoaderListener(ctx));

        ServletRegistration.Dynamic servlet 
          = container.addServlet("dispatcher", new DispatcherServlet(ctx));

3.5. Testing Spring Mvc Validation Using Curl

3.5.使用Curl测试Spring Mvc的验证

Before we implement the AngularJS client section, we can test our API using cURL with the command:


curl -i -X POST -H "Accept:application/json" 

The response is an array containing the default error messages:


    "not a well-formed email address",
    "size must be between 4 and 15",
    "may not be empty",
    "must be greater than or equal to 18"

4. AngularJS Validation


Client-side validation is useful in creating a better user experience, as it provides the user with information on how to successfully submit valid data and enables them to be able to continue to interact with the application.


The AngularJS library has great support for adding validation requirements on form fields, handling error messages, and styling valid and invalid forms.


First, let’s create an AngularJS module that injects the ngMessages module, which is used for validation messages:


var app = angular.module('app', ['ngMessages']);

Next, let’s create an AngularJS service and controller that will consume the API built in the previous section.


4.1. The AngularJS Service


Our service will have two methods that call the MVC controller methods — one to save a user, and one to retrieve the list of users:


app.service('UserService',['$http', function ($http) {
    this.saveUser = function saveUser(user){
        return $http({
          method: 'POST',
          url: 'user',
          params: {, password:user.password, 
  , age:user.age},
          headers: 'Accept:application/json'
    this.getUsers = function getUsers(){
        return $http({
          method: 'GET',
          url: 'users',
        }).then( function(response){
        } );


4.2. The AngularJS Controller


The UserCtrl controller injects the UserService, calls the service methods and handles the response and error messages:


app.controller('UserCtrl', ['$scope','UserService', function ($scope,UserService) {
	$scope.submitted = false;
	$scope.getUsers = function() {
		   UserService.getUsers().then(function(data) {
		       $scope.users = data;
    $scope.saveUser = function() {
    	$scope.submitted = true;
    	  if ($scope.userForm.$valid) {
              .then (function success(response) {
                  $scope.message = 'User added!';
                  $scope.errorMessage = '';
                  $scope.user = null;
                  $scope.submitted = false;
              function error(response) {
                  if (response.status == 409) {
                    $scope.errorMessage =;
            	  else {
                    $scope.errorMessage = 'Error adding user!';
                  $scope.message = '';

We can see in the example above that the service method is called only if the $valid property of userForm is true. Still, in this case, there is the additional check for duplicate emails, which can only be done on the server and is handled separately in the error() function.


Also, notice that there is a submitted variable defined which will tell us if the form has been submitted or not.


Initially, this variable will be false, and on invocation of the saveUser() method, it becomes true. If we don’t want validation messages to show before the user submits the form, we can use the submitted variable to prevent this.


4.3. Form Using AngularJS Validation


In order to make use of the AngularJS library and our AngularJS module, we will need to add the scripts to our user.html page:


<script src="">
<script src="">
<script src="js/app.js"></script>

Then we can use our module and controller by setting the ng-app and ng-controller properties:


<body ng-app="app" ng-controller="UserCtrl">

Let’s create our HTML form:


<form name="userForm" method="POST" novalidate 
  ng-class="{'form-error':submitted}" ng-submit="saveUser()" >

Note that we have to set the novalidate attribute on the form in order to prevent default HTML5 validation and replace it with our own.


The ng-class attribute adds the form-error CSS class dynamically to the form if the submitted variable has a value of true.

如果submitted变量的值为trueng-class属性会将form-error CSS类动态地添加到表单中。

The ng-submit attribute defines the AngularJS controller function that will be called when the form in submitted. Using ng-submit instead of ng-click has the advantage that it also responds to submitting the form using the ENTER key.


Now let’s add the four input fields for the User attributes:


<label class="form-label">Email:</label>
<input type="email" name="email" required ng-model="" class="form-input"/>

<label class="form-label">Password:</label>
<input type="password" name="password" required ng-model="user.password" 
  ng-minlength="4" ng-maxlength="15" class="form-input"/>

<label class="form-label">Name:</label>
<input type="text" name="name" ng-model="" ng-trim="true" 
  required class="form-input" />

<label class="form-label">Age:</label>
<input type="number" name="age" ng-model="user.age" ng-min="18"
  class="form-input" required/>

Each input field has a binding to a property of the user variable through the ng-model attribute.


For setting validation rules, we use the HTML5 required attribute and several AngularJS-specific attributes: ng-minglength, ng-maxlength, ng-min, and ng-trim.

对于设置验证规则,我们使用HTML5的required属性和几个AngularJS特有的属性。ng-minglength, ng-maxlength, ng-min, ng-trim

For the email field, we also use the type attribute with a value of email for client-side email validation.


In order to add error messages corresponding to each field, AngularJS offers the ng-messages directive, which loops through an input’s $errors object and displays messages based on each validation rule.


Let’s add the directive for the email field right after the input definition:


<div ng-messages="$error" 
  ng-show="submitted &&$invalid" class="error-messages">
    <p ng-message="email">Invalid email!</p>
    <p ng-message="required">Email is required!</p>

Similar error messages can be added for the other input fields.


We can control when the directive is displayed for the email field using the ng-show property with a boolean expression. In our example, we display the directive when the field has an invalid value, meaning the $invalid property is true, and the submitted variable is also true.


Only one error message will be displayed at a time for a field.


We can also add a check mark sign (represented by HEX code character ✓) after the input field in case the field is valid, depending on the $valid property:


<div class="check" ng-show="$valid">✓</div>

AngularJS validation also offers support for styling using CSS classes such as ng-valid and ng-invalid or more specific ones like ng-invalid-required and ng-invalid-minlength.


Let’s add the CSS property border-color:red for invalid inputs inside the form’s form-error class:


.form-error {

We can also show the error messages in red using a CSS class:


.error-messages {

After putting everything together, let’s see an example of how our client-side form validation will look when filled out with a mix of valid and invalid values:


AngularJS form validation example

5. Conclusion


In this tutorial, we’ve shown how we can combine client-side and server-side validation using AngularJS and Spring MVC.

在本教程中,我们展示了如何使用AngularJS和Spring MVC结合客户端和服务器端验证。

As always, the full source code for the examples can be found over on GitHub.


To view the application, access the /userPage URL after running it.

要查看应用程序,运行后访问/userPage URL。