Custom Validation

Activity:

Custom alidation Demo 
First name: John 
Last name: Doe 
Course Code: ABC1234 
&Jbmit 
Course code must start with LUV

Custom validation

  • Perform custom validation based on your business rules
    • Our example: Course Code must start with “KVT”
  • Spring MVC calls our custom validation
  • Custom validation returns Boolean value for pass/fail (true/false)
Create a custom Java Annotation ... from scratch 
+ so far, we've used predefined validation rules: @Min, @Max, ... 
+ For custom valid 
+ @CourseC0de 
tom Jav 
validatim 
message="must start with LUV") 
private String courseCode;

Development Process

  1. Create custom validation rule
  1. Add validation rule to Customer class
  2. Display error message on HTML form
  3. Update confirmation page
Development Process - Drill Down 
1. Create custom validation rule 
a. Create @CourseCode annotation 
b. Create CourseCodeConstraintValidator 
Helper class 
Contains our custom 
business logic for validation
Step la: Create @CourseCode annotation 
CourseCodeConstraintVa1idator .class) 
garget( { ElementType.METHOD, ElementType.FIELD ) ) 
@Retention(RetentionP01icy. RUNTIME) 
public @interface CourseCode { 
Default value 
// define default course code 
public String value() default "LUV" ; 
// define default error message 
public String message() default "must start with LUV" ; 
@CourseCode(va1ue="LUV", message="must start with LUV") 
private String courseC0de;

Breaking from up top

//  “CourseCodeConstrainValidator.class” is the actual business class that is validating this process. Its an helper class that will contain business rules/ validation logic

@Constraint(validatedBy = CourseCodeConstrainValidator.class)

@Target : tells custom annotation can apply our annotation to method or field

@Retention : Retain this annotation in the Java class file (complied java byte code). Process it at runtime

Parameter Attribute  are the default values which can be override

Below is the basic layout of the code:

import java*. validation.C0nstraintValidator; 
java*. validation. ConstraintValidatorContext; 
public class CourseC0deConstraintValidator 
i.lements ConstraintValidatorcCourseCode. String' 
private String coursePrefix; 
r r i de 
public void initialize 
coursePrefix theCou. - 
Our 
annotation 
ode) { 
Type Of data to 
v•IOte

In this initialize method, we can get actual prefix of value and that value will be stored in a variable “coursePrefix“.

public class CourseC0deConstraintValidator 
i.lements ConstraintValidatorcCourseCode, 
private String coursePrefix; 
•ve r ri de 
String' 
public void initialize(CourseCode theCourseCode) { 
coursePrefix • theCourseCode. 
@0verride 
public boolean 
Const ra 
boolean result; 
, message: 
private String 
"must start with WV") 
if (theCOde null) ( 
result • thecode. startsWith(coursePrefix); 
else { 
result true; 
return result;

At this point our validator is up and running and now someone can use  it. By using boolean method.

@0verride 
public boolean i SVaIid(String theCode, 
ConstraintValidatorContext theConstraintValidat0rContext) { 
boolean result; 
if (theCOde null) { 
result • theCode.startsWith(coursePrefix); 
else { 
result true; 
Spring MVC will call: isValid(...)
HTML Form Data 
Entend by ttw 
public boolean theCode, 
ConstraintValidatorContext theConstraintValidatorContext) { 
boolean result; 
if (theCOde null) { 
result • theCode. startsHith(coursePrefix); 
else { 
result true; 
return result; 
class 'or
@0verride 
public boolean theCode, 
ConstraintValidatorContext theConstr 
boolean result; 
if (theCode null) ( 
result • theCode.startsWith(coursePrefix); 
else { 
r•esult true; 
return result; 
Test torm data Starts 
does it start with
if (theCOde 
result 
else { 
result 
null) { 
theCode. startsuith(courseprefix) ; 
true ; 
Wst 
return result;

Lets start coding our activity

Create a new @Annotation

spring-mvc-demo [spring-mvc-demo main] 
> JAX-WS Web Services 
v " Java Resources 
> comhrtsoft.springdemo.mvc 
messages. properties 
Libraries 
com.kvtsoft.springdemo.mvc.validation 
build 
WebContent 
> META-INF 
resources 
v h WEB-INF 
lib 
cookie.jsp 
> customer-confirmation.jsp 
> customer-form.jsp 
enrollment.jsp 
enrollment-form.jsp 
fortune-form.jsp 
main-menu.Jsp 
student-confirmation.jsp 
student-form.jsp 
> spring-mvc-demo-servlet.xml 
web.xml 
LICENSE 
README.md 
New Annotation Type 
Annotation Type 
Create a new annotation type. 
Source folder: 
Package: 
• Enclosing tupe 
Modfiers: 
Add @ßetention: 
Add 
spring- mvc-demo/src 
com.kvtsoft.springdemo.mvc.validation 
CourseCode 
O public 
package 
Add @Documented 
Do you want to add comments? (Configure templates and default value hue) 
• Generate comments 
Finish 
Browse... 
Browse... 
Cancel

// define default groups (group validation constrain together)

// groups: can group related constraints

// define default pay load (gives additional info about the error)

// Payloads: provide custom details about the validation failure (security level, error code etc)

CourseCode  @Annotation

Create CourseCodeConstraintValidator.java

Result:

http://IccaIhcst:8D80/spring-mvc-demc/custcmer/prccessFcrm 
Fill out the form. All the fields with Asterisk (8) are required. 
First name: 
Last name (*) is requried 
Free passes is required 
Postal code:@öj@::::::::::::::::::::::::::::::::::::::::::::::::] 
Course code: 
must start with KVT 
Submit

Leave a comment