Spring MVC Tutorial

Spring MVC Custom Validator Annotation

Spring mvc custom validator annotation

Spring mvc custom validator annotation with constraintvalidator example interface using maven and eclipse.

package com.candidjava.spring.bean;

import java.util.List;

import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

import com.candidjava.spring.validator.Email;
import com.candidjava.spring.validator.Phone;

public class User 
{	
  @NotNull
  @Size(min=1)
  private String name;
  
  @NotNull
  @Size(min=1)
  private List<String> language;
  
  @Size(min=1)
  private String country;
  
  @NotNull
  private String gender;
  
  @Size(min=8, max=20)
  private String password;
  @Phone
  private String phone; 
  public String getPhone() {
    return phone;
  }

  public void setPhone(String phone) {
    this.phone = phone;
  }

  @Email
  @Size(min=1)
  private String email;

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public List<String> getLanguage() {
    return language;
  }

  public void setLanguage(List<String> language) {
    this.language = language;
  }

  public String getCountry() {
    return country;
  }

  public void setCountry(String country) {
    this.country = country;
  }

  public String getGender() {
    return gender;
  }

  public void setGender(String gender) {
    this.gender = gender;
  }

  public String getPassword() {
    return password;
  }

  public void setPassword(String password) {
    this.password = password;
  }

  public String getEmail() {
    return email;
  }

  public void setEmail(String email) {
    this.email = email;
  }	
}

Spring constraintValidator

Phone.java

package com.candidjava.spring.validator;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import javax.validation.Constraint;
import javax.validation.Payload;


@Documented
@Constraint(validatedBy = EmailConstraintValidator.class)
@Target({ElementType.METHOD,ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Email
{

  String message() default "{Email}";
  
  Class<?>[] groups() default {};
  
  Class<? extends Payload>[] payload() default {};

}

PhoneValidator.java

package com.candidjava.spring.validator;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

public class PhoneValidator implements ConstraintValidator<Phone, String> {

  @Override
  public void initialize(Phone paramA) {
  }

  @Override
  public boolean isValid(String phoneNo, ConstraintValidatorContext ctx) {
    if(phoneNo == null){
      return false;
    }
    //validate phone numbers of format "1234567890"
        if (phoneNo.matches("\\d{10}")) return true;
        //validating phone number with -, . or spaces
        else if(phoneNo.matches("\\d{3}[-\\.\\s]\\d{3}[-\\.\\s]\\d{4}")) return true;
        //validating phone number with extension length from 3 to 5
        else if(phoneNo.matches("\\d{3}-\\d{3}-\\d{4}\\s(x|(ext))\\d{3,5}")) return true;
        //validating phone number where area code is in braces ()
        else if(phoneNo.matches("\\(\\d{3}\\)-\\d{3}-\\d{4}")) return true;
        //return false if nothing matches the input
        else return false;
  }

}

Email.java

package com.candidjava.spring.validator;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import javax.validation.Constraint;
import javax.validation.Payload;


@Documented
@Constraint(validatedBy = EmailConstraintValidator.class)
@Target({ElementType.METHOD,ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Email
{

  String message() default "{Email}";
  
  Class<?>[] groups() default {};
  
  Class<? extends Payload>[] payload() default {};

}

EmailConstraintValidator.java

package com.candidjava.spring.validator;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import javax.validation.Constraint;
import javax.validation.Payload;


@Documented
@Constraint(validatedBy = EmailConstraintValidator.class)
@Target({ElementType.METHOD,ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Email
{

  String message() default "{Email}";
  
  Class<?>[] groups() default {};
  
  Class<? extends Payload>[] payload() default {};

}

Spring Controller

package com.candidjava.spring.controller;


import javax.validation.Valid;

import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.ModelAndView;

import com.candidjava.spring.bean.User;

@Controller
public class UserController {
  
  User users = new User();
  @GetMapping("index")
  public ModelAndView register(User user) {
    return new ModelAndView("register");
  }

  @PostMapping("/register")
  public ModelAndView create(@Valid User user, BindingResult bindingResult) {
    ModelAndView model = new ModelAndView("view");
    // user bean will be automatically binded to view refer @ModelAttribute
    if(bindingResult.hasErrors())
    {
      return new ModelAndView("register");
    }
      users.setName(user.getName());
      users.setEmail(user.getEmail());
      users.setGender(user.getGender());
      users.setLanguage(user.getLanguage());
      users.setCountry(user.getCountry());
      users.setPassword(user.getPassword());
    return model;
  }

  @GetMapping("/register")
  public ModelAndView viewData(User user) {

    ModelAndView model = new ModelAndView("register");
    return model;
  }

}

Spring Resource file

Size.user.name = please enter name
NotNull.user.gender = Please specify your gender
Size.user.country = Please select your country
Size.user.language= Please select at least one language
Size.user.password = password must be between 8 and 20
Size.user.email=Email field can't be blank
typeMismatch=Invalid format
Email=please enter valid email address
Phone=please enter Valid phone number

JSP view

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<style type="text/css">
.err
{
color:red;
}
</style>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>

<body>

  <h2>Simple spring form handling</h2>
  <form:form action="register" method="POST" modelAttribute="user">
  Name:<form:input path="name"/><p><form:errors path="name" class="err"/></p><br>
Gender : Male<form:radiobutton name="gender" value="male" path="gender"/>   Female<form:radiobutton  name="gender" value="female" path="gender"/><p><form:errors path="gender"  class="err"/></p><br>
  Email : <form:input  path="email"/><p><form:errors path="email"  class="err"/></p><br>
  Phone : <form:input  path="phone"/><p><form:errors path="phone"  class="err"/></p><br>
  Languages : English<form:checkbox   value="english" path="language" /> French<form:checkbox  value="french" path="language"/> Tamil<form:checkbox  value="tamil" path="language"/><p><form:errors path="language"  class="err"/></p><br>
  Country : <form:select path="country">
          <form:option value="">select country</form:option>
          <form:option value="india">INDIA</form:option>
          <form:option value="usa">USA</form:option>
          <form:option value="china">CHINA</form:option>
         </form:select>
         <p><form:errors path="country" class="err"/></p>
         
        <br>  
        Password:<form:password path="password"/><p><form:errors path="password" class="err"/></p><br>  
        <input type="submit" value="submit" />
  </form:form>
</body>
</html>

 

Download

Spring 4 form ConstraintValidator example war

Spring 4 form ConstraintValidator example maven zip