close

Filter

loading table of contents...

Content Application Developer Manual / Version 2207

Table Of Contents
4.3.6.3.2 Associate a validator with a form bean

To validate a form bean with a validator in the context of a handler, add an @InitBinder annotated method to the handler:

@InitBinder("nameOfForm")
protected void initBinder(WebDataBinder binder) {
  binder.setValidator(new MyFormValidator());
}
Note

Note

Do not forget the form name, otherwise the validator will be applied to any @ModelAttribute or @PathVariable arguments.

To actually validate the form bean, annotate the method parameter with @Valid.

public ModelAndView handleFormSubmit(
      @ModelAttribute("nameOfForm") @Valid MyForm form, ...)

This is an example validator that implements all necessary methods for the example use case of validating the MyForm example shown before:

import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

import java.util.regex.Pattern;

/**
 * Validator for {@link MyForm}
 */
public class MyFormValidator implements Validator {

  /**
   * this pattern matches an email address such as "test@test.com"
   */
  private static final Pattern EMAILADDRESS_PATTERN =
          Pattern.compile("\\b[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,4}\\b");

  @Override
  public boolean supports(Class<?> clazz) {
    return MyForm.class.isAssignableFrom(clazz);
  }

  @Override
  public void validate(Object target, Errors errors) {

    MyForm form = (MyForm) target;

    //use Spring Utility to validate if form field is empty
    ValidationUtils.rejectIfEmptyOrWhitespace(
            errors,
            "email",
            "error-email-missing",
            "Email is missing");

    //if form field has content, validate if format matches email pattern
    if (!errors.hasErrors()) {

      if (!isValidEmail(form.getEmail())) {
        errors.rejectValue(
                "email",
                "error-email-format",
                "Not a valid email address");
      }
      //and if form field contents match each other.
      else if (!form.getEmail().equals(form.getEmailRepeat())) {
        errors.reject(
                "error-email-no-match",
                "Emails are not equal");
      }
    }
  }

  /**
   * @return true if email matches the pattern
   */
  protected boolean isValidEmail(String email) {
    return EMAILADDRESS_PATTERN.matcher(email).matches();
  }

}

Search Results

Table Of Contents
warning

Your Internet Explorer is no longer supported.

Please use Mozilla Firefox, Google Chrome, or Microsoft Edge.