By kswaughs | Monday, November 9, 2015

Spring Web MVC Custom Validator

This post describes how to use Spring Custom Validator to perform the input form validations with examples.

Create a model object to hold the input form values.

Data Model class to hold user name
public class UserBean {

 private String userName;

 public String getUserName() {
  return userName;
 }

 public void setUserName(String userName) {
  this.userName = userName;
 }
}

Create a custom validator class and use ValidationUtils with custom error messages.

Validator class
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

@Component
public class UserValidator implements Validator{

 @Override
 public boolean supports(Class paramClass) {

  return UserBean.class.equals(paramClass);
 }

 @Override
 public void validate(Object arg0, Errors errors) {
  ValidationUtils.rejectIfEmptyOrWhitespace(errors, "userName", 
       "error.userName" , "Invalid user name");
 }
}

In controller, Call this validate method and handle as below.

Controller method
@RequestMapping(value = "/user", method = RequestMethod.POST)
public String processUser(@ModelAttribute UserBean userBean, BindingResult result) {

    UserValidator.validate(userBean, result);

    if( ! result.hasErrors()) {
       return "success";
    }

    return "input";
}

In your input.jsp page, add this below element where you want to show the message

<form:errors path="userName" cssStyle="color: #ff0000;"/>

Recommend this on


No comments:

Post a Comment