Spring MVC Custom Validation

1. Overview

Generally, when we need to validate user input, Spring MVC offers standard predefined validators.

However, when we need to validate a more particular type of input, we have the possibility of creating our own, custom validation logic.

In this article, we’ll do just that – we’ll create a custom validator to validate a form with a phone number field, then show a custom validator for multiple fields.

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

2. Setup

To benefit from the API, add the dependency to your pom.xml file:

<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-validator</artifactId>
    <version>6.0.10.Final</version>
</dependency>

The latest version of the dependency can be checked here.

If we’re using Spring Boot, then we can add only the spring-boot-starter-web, which will bring in the hibernate-validator dependency also.

3. Custom Validation

Creating a custom validator entails us rolling out our own annotation and using it in our model to enforce the validation rules.

So, let’s create our custom validator – which checks phone numbers. The phone number must be a number with more than eight digits but no more than 11 digits.

4. The New Annotation

Let’s create a new @interface to define our annotation:

@Documented
@Constraint(validatedBy = ContactNumberValidator.class)
@Target( { ElementType.METHOD, ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
public @interface ContactNumberConstraint {
    String message() default "Invalid phone number";
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};
}

With the @Constraint annotation, we defined the class that is going to validate our field, the message() is the error message that is showed in the user interface and the additional code is most boilerplate code to conforms to the Spring standards.

5. Creating a Validator

Let’s now create a validator class that enforces the rules of our validation:

public class ContactNumberValidator implements 
  ConstraintValidator<ContactNumberConstraint, String> {

    @Override
    public void initialize(ContactNumberConstraint contactNumber) {
    }

    @Override
    public boolean isValid(String contactField,
      ConstraintValidatorContext cxt) {
        return contactField != null && contactField.matches("[0-9]+")
          && (contactField.length() > 8) && (contactField.length() < 14);
    }

}

The validation class implements the ConstraintValidator interface and must implement the isValid method; it’s in this method that we defined our validation rules.

Naturally, we’re going with a simple validation rule here, to show how the validator works.

ConstraintValidator defines the logic to validate a given constraint for a given object. Implementations must comply with the following restriction:

  • the object must resolve to a non-parametrized type
  • generic parameters of the object must be unbounded wildcard types

6. Applying Validation Annotation

In our case, we’ve created a simple class with one field to apply the validation rules. Here, we’re setting up our annotated field to be validated:

@ContactNumberConstraint
private String phone;

We defined a string field and annotated it with our custom annotation @ContactNumberConstraint. In our controller we created our mappings and handled the error if any:

@Controller
public class ValidatedPhoneController {
 
    @GetMapping("/validatePhone")
    public String loadFormPage(Model m) {
        m.addAttribute("validatedPhone", new ValidatedPhone());
        return "phoneHome";
    }
    
    @PostMapping("/addValidatePhone")
    public String submitForm(@Valid ValidatedPhone validatedPhone,
      BindingResult result, Model m) {
        if(result.hasErrors()) {
            return "phoneHome";
        }
        m.addAttribute("message", "Successfully saved phone: "
          + validatedPhone.toString());
        return "phoneHome";
    }   
}

We defined this simple controller that has a single JSP page, and use the submitForm method to enforce the validation of our phone number.

7. The View

Our view is a basic JSP page with a form that has a single field. When the user submits the form, then the field gets validated by our custom validator and redirects to the same page with the message of successful or failed validation:

<form:form 
  action="/${pageContext.request.contextPath}/addValidatePhone"
  modelAttribute="validatedPhone">
    <label for="phoneInput">Phone: </label>
    <form:input path="phone" id="phoneInput" />
    <form:errors path="phone" cssClass="error" />
    <input type="submit" value="Submit" />
</form:form>

8. Tests

Let’s now test our controller and check if it’s giving us the appropriate response and view:

@Test
public void givenPhonePageUri_whenMockMvc_thenReturnsPhonePage(){
    this.mockMvc.
      perform(get("/validatePhone")).andExpect(view().name("phoneHome"));
}

Also, let’s test that our field is validated, based on user input:

@Test
public void 
  givenPhoneURIWithPostAndFormData_whenMockMVC_thenVerifyErrorResponse() {
 
    this.mockMvc.perform(MockMvcRequestBuilders.post("/addValidatePhone").
      accept(MediaType.TEXT_HTML).
      param("phoneInput", "123")).
      andExpect(model().attributeHasFieldErrorCode(
          "validatedPhone","phone","ContactNumberConstraint")).
      andExpect(view().name("phoneHome")).
      andExpect(status().isOk()).
      andDo(print());
}

In the test, we’re providing a user with the input of “123, ” and – as we expected – everything’s working and we’re seeing the error on the client side.

9. Custom Class Level Validation

A custom validation annotation can also be defined at the class level to validate more than one attribute of the class.

A common use case for this scenario is verifying if two fields of a class have matching values.

9.1. Creating the Annotation

Let’s add a new annotation called FieldsValueMatch that can be later applied to a class. The annotation will have two parameters field and fieldMatch that represent the names of the fields to compare:

@Constraint(validatedBy = FieldsValueMatchValidator.class)
@Target({ ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
public @interface FieldsValueMatch {

    String message() default "Fields values don't match!";

    String field();

    String fieldMatch();

    @Target({ ElementType.TYPE })
    @Retention(RetentionPolicy.RUNTIME)
    @interface List {
        FieldsValueMatch[] value();
    }
}

We can see our custom annotation also contains a List sub-interface for defining multiple FieldsValueMatch annotations on a class.

9.2. Creating the Validator

Next, we need to add the FieldsValueMatchValidator class that will contain the actual validation logic:

public class FieldsValueMatchValidator 
  implements ConstraintValidator<FieldsValueMatch, Object> {

    private String field;
    private String fieldMatch;

    public void initialize(FieldsValueMatch constraintAnnotation) {
        this.field = constraintAnnotation.field();
        this.fieldMatch = constraintAnnotation.fieldMatch();
    }

    public boolean isValid(Object value, 
      ConstraintValidatorContext context) {

        Object fieldValue = new BeanWrapperImpl(value)
          .getPropertyValue(field);
        Object fieldMatchValue = new BeanWrapperImpl(value)
          .getPropertyValue(fieldMatch);
        
        if (fieldValue != null) {
            return fieldValue.equals(fieldMatchValue);
        } else {
            return fieldMatchValue == null;
        }
    }
}

The isValid() method retrieves the values of the two fields and checks if they are equal.

9.3. Applying the Annotation

Let’s create a NewUserForm model class intended for data required for user registration, that has two email and password attributes, along with two verifyEmail and verifyPassword attributes to re-enter the two values.

Since we have two fields to check against their corresponding matching fields, let’s add two @FieldsValueMatch annotations on the NewUserForm class, one for email values, and one for password values:

@FieldsValueMatch.List({ 
    @FieldsValueMatch(
      field = "password", 
      fieldMatch = "verifyPassword", 
      message = "Passwords do not match!"
    ), 
    @FieldsValueMatch(
      field = "email", 
      fieldMatch = "verifyEmail", 
      message = "Email addresses do not match!"
    )
})
public class NewUserForm {
    private String email;
    private String verifyEmail;
    private String password;
    private String verifyPassword;

    // standard constructor, getters, setters
}

To validate the model in Spring MVC, let’s create a controller with a /user POST mapping that receives a NewUserForm object annotated with @Valid and verifies whether there are any validation errors:

@Controller
public class NewUserController {

    @GetMapping("/user")
    public String loadFormPage(Model model) {
        model.addAttribute("newUserForm", new NewUserForm());
        return "userHome";
    }

    @PostMapping("/user")
    public String submitForm(@Valid NewUserForm newUserForm, 
      BindingResult result, Model model) {
        if (result.hasErrors()) {
            return "userHome";
        }
        model.addAttribute("message", "Valid form");
        return "userHome";
    }
}

9.4. Testing the Annotation

To verify our custom class-level annotation, let’s write a JUnit test that sends matching information to the /user endpoint, then verifies that the response contains no errors:

public class ClassValidationMvcTest {
  private MockMvc mockMvc;
    
    @Before
    public void setup(){
        this.mockMvc = MockMvcBuilders
          .standaloneSetup(new NewUserController()).build();
    }
    
    @Test
    public void givenMatchingEmailPassword_whenPostNewUserForm_thenOk() 
      throws Exception {
        this.mockMvc.perform(MockMvcRequestBuilders
          .post("/user")
          .accept(MediaType.TEXT_HTML).
          .param("email", "john@yahoo.com")
          .param("verifyEmail", "john@yahoo.com")
          .param("password", "pass")
          .param("verifyPassword", "pass"))
          .andExpect(model().errorCount(0))
          .andExpect(status().isOk());
    }
}

Next, let’s also add a JUnit test that sends non-matching information to the /user endpoint and assert that the result will contain two errors:

@Test
public void givenNotMatchingEmailPassword_whenPostNewUserForm_thenOk() 
  throws Exception {
    this.mockMvc.perform(MockMvcRequestBuilders
      .post("/user")
      .accept(MediaType.TEXT_HTML)
      .param("email", "john@yahoo.com")
      .param("verifyEmail", "john@yahoo.commmm")
      .param("password", "pass")
      .param("verifyPassword", "passsss"))
      .andExpect(model().errorCount(2))
      .andExpect(status().isOk());
    }

10. Summary

In this quick article, we have shown how to create custom validators to verify a field or class and wire them into Spring MVC.

As always, you can find the code from the article over on Github.