Tuesday, April 12, 2022

Spring boot 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 ability to create our own custom validation logic. 



In this tutorial, we'll do just that; we'll create a custom validator to validate a form with a phone number field, and then we'll show a custom validator for multiple fields.

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

2. Setup

To benefit from the API, we'll add the dependency to our 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 only add the spring-boot-starter-web, which will bring in the hibernate-validator dependency also.

3. Custom Validation 

Creating a custom validator entails 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 at least 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. Finally, the additional code is mostly boilerplate code to conform to the Spring standards.

5. Creating a Validator 

Now let's 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 also 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 in order 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 restrictions:

  • 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 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 any errors:

@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 used 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, the field gets validated by our custom validator and redirects to the same page with a 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

Now let's test our controller to 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"));
}

Let's also 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 the data required for user registration. It will have 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());
    }
}

Then we'll also add a JUnit test that sends non-matching information to the /user endpoint and asserts 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());
    }

No comments:

Post a Comment

So sánh các GitFlow model và áp dụng với CICD

https://medium.com/oho-software/so-s%C3%A1nh-c%C3%A1c-gitflow-model-v%C3%A0-%C3%A1p-d%E1%BB%A5ng-v%E1%BB%9Bi-cicd-b6581cfc893a