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 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.
2. Setup
To benefit from the API, add the dependency to your pom.xml file:
<dependency> <groupId>javax.validation</groupId> <artifactId>validation-api</artifactId> <version>1.1.0.Final</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <version>5.4.1.Final</version> </dependency>
The latest version of the dependency can be checked here and here.
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 that 11 digits.
4. The New Annotation
Let’s create a new @interface with the 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 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 @EnableWebMvc 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 have 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. Summary
In this quick article, we created a custom validator to verify a field and wired that into Spring MVC.
As always, you can find the code from the article over on Github.