Form Validation – part 5 (writing a custom Form Validation annotation)

Custom Form Validation Annotation

Suppose we have a requirement where we do not have a build in annotation provided for any specific requirement for you own project than in that case Spring Framework provides Developer to create Custom Form Validation Annotation and then used this annotation like any other build in annotation in your application

For Example : Suppose we have a requirement where we want the user to enter hobby from a set of already defined hobby, for example [skating,music,reading] and if user enters a hobby other than this then our Application should throw a validation message.

Let see how we can achieve this

Steps to create a Custom Form Validation Annotation with the nameIsValidHobby

  1. Create a Java file(called as an annotation type or simply an interface) having complete definition of this custom annotation like name of the custom annotation,the default error message information etc
  2. Create a Java file(a class) – having the validation logic used by the custom annotation to validate the user input

Code for IsValidHobby.java which has complete defination of the Custom Form Validation @IsValidHobby that we will be using in our Student.java file

IsValidHobby.java

package com.technicalstack.studentRegistrationController;

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 org.springframework.messaging.handler.annotation.Payload;

@Documented
@Constraint(validatedBy = HobbyValidator.class)
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)

public @interface IsValidHobby {

String message() default “Please enter a valid hobby “+”Options values are – Skating,Music,Reading(Provide anyone)”;

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

}

Here all the code that is in blue colour is mandatory when we write any Custom Form Validator

The message in yellow is the default message that would be displayed on the page.

Code for HobbyValidator.java

 

Now,we will use the custom validator in our Student.java file as below

@Size(min=3, max=25)@IsValidHobby
private String studentHobby;

Next to test this ,we will run our application and enter a hobby [Traveling] which is not as predefined one[Skating,Music,Reading] and submit the form.

customannotation4

Our Application will give the expected  default error message which we have defined in our IsValidHobby.java file

customannotation5


   

Comments are closed