In this tutorial, I am going to show you how to validate Spring Form with Custom validations.
In the previous tutorial, we had a discussion about a simple and basic form validation of spring form. For this Spring Form Custom Validation I am going to take the basic form to some extent.
Technologies :
- Spring Framework 3.1.1.RELEASE
- Hibernate Validator 4.2.0.Final
- Jstl 1.2
- Java 8
Spring Form Custom Validation :
Project Structure :
Create your own annotation for custom validation.
Recommended : Spring Boot Login From Validation Example
CouponCode.java
I am going to create CouponCode anotation which validates whether provided coupon code valid or not.
[java]
package com.spring.customannotation;
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;
@Constraint(validatedBy = CouponCodeValidator.class)
@Target({ElementType.METHOD, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface CouponCode {
public String value() default "OTP";
public String message() default "Coupon Code must starts with OTP";
public Class<?>[] groups() default {};
public Class<? extends Payload>[] payload() default{};
}
[/java]
Applying Constraint validation using validation framework.
CouponCodeValidator.java
[java]
package com.spring.customannotation;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
public class CouponCodeValidator implements ConstraintValidator<CouponCode, String> {
private String couponCodePrefix;
public void initialize(CouponCode couponCode) {
couponCodePrefix = couponCode.value();
}
/*
* You can write your own validation logic here. For now I am doing simple validation here like
* checking whether coupon code startes with "OTP" or not.
*/
public boolean isValid(String couponCode, ConstraintValidatorContext constraintValidatorContext) {
if (couponCode != null) {
return couponCode.startsWith(couponCodePrefix);
} else {
return true;
}
}
}
[/java]
Coupon code is valid iff, it startes with “OTP” otherwise it will throw default message like “Coupon Code must starts with OTP”.
RegistrationBean.java
[java]
package com.spring.controller;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
import com.spring.customannotation.CouponCode;
public class RegistrationBean {
@NotNull
@Size(min = 1, message = "You can’t leave this empty.")
private String firstName;
@NotNull
@Size(min = 1, message = "You can’t leave this empty.")
private String lastName;
@NotNull(message = "You can’t leave this empty.")
@Min(value = 13, message = "You must be greater than or equal to 13")
@Max(value = 19, message = "You must be less than or equal to 19")
private Integer age;
@Pattern(regexp = "^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,6}$", message = "Invalid email")
private String email;
@CouponCode
private String couponCode;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getCouponCode() {
return couponCode;
}
public void setCouponCode(String couponCode) {
this.couponCode = couponCode;
}
}
[/java]
RegistrationController.java
[java]
package com.spring.controller;
import javax.validation.Valid;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
public class RegistrationController {
@RequestMapping(value = "/register", method = RequestMethod.GET)
public String showForm(Model model) {
model.addAttribute("registration", new RegistrationBean());
return "register";
}
@RequestMapping(value = "/processForm", method = RequestMethod.POST)
public String processForm(@Valid @ModelAttribute("registration") RegistrationBean register,
BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
return "register";
} else {
return "success";
}
}
}
[/java]
register.jsp
[html]</pre>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Spring MVC Form Validation</title>
<style>
.error {
color: red
}
</style>
</head>
<body>
<form:form action="processForm" modelAttribute="registration">
<div align="center">
<h2>Register Here</h2>
<table>
<tr>
<td>First name</td>
<td><form:input type="text" path="firstName" /></td>
<td><form:errors path="firstName" cssClass="error" /></td>
</tr>
<tr>
<td>Last name (*)</td>
<td><form:input type="text" path="lastName" /></td>
<td><form:errors path="lastName" cssClass="error" /></td>
</tr>
<tr>
<td>Age </td>
<td><form:input type="text" path="age" /></td>
<td><form:errors path="age" cssClass="error" /></td>
</tr>
<tr>
<td>Email </td>
<td><form:input type="text" path="email" /></td>
<td><form:errors path="email" cssClass="error" /></td>
</tr>
<tr>
<td>Coupon Code </td>
<td><form:input type="text" path="couponCode" /></td>
<td><form:errors path="couponCode" cssClass="error" /></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Submit" /></td>
</tr>
</table>
</div>
</form:form>
</body>
</html>
<pre>[/html]
success.jsp :
[html]
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Registration Confirmation</title>
</head>
<body>
Hello <font color="green">${registration.firstName} ${registration.lastName} </font> you have successfully registered with us.
</body>
</html>
[/html]
Test your Application :
http://localhost:8080/Spring-MVC-Custom-Form-Validation/register
Giving valid coupon code.
Success.jsp
Happy Learning 🙂