Spring MVC Form Validation - Creating Custom Validation Rule

Custom Validation



Creating a custom validator entails us rolling out our own annotation and using it in our model to enforce the validation rules.

So, let's create our custom validator – which checks course code. The course code must starts with "LUV".
The New Annotation
Let's now create a validator class that enforces rules of our validation:

The validation class implements the ConstraintValidator interface and must implement the isValid method; it's in this method that we defined our validation rules.

Naturally, we're going with a simple validation rule here, to show how the validator works.
ConstraintValidator defines the logic to validate a given constraint for a given object. Implementations must comply with the following restriction:
  • the object must resolve to a non-parametrized type
  • generic parameters of the object must be unbounded wildcard types
Applying Validation Annotation
We defined a string field and annotated it with our custom annotation @CourseCode. In our controller we created our mappings and handled the error if any:

Comments

Popular posts from this blog

Use @Initbinder in Spring MVC

Nginx

AWS Configuration For RDS(postgres),ElastiCache(Redis) with ElasticBean

Different ways to Authenticate a Web Application

The TRUE difference between [] and {{}} bindings in Angular

Why you should use BCrypt to hash passwords

CSRF Protection using Double Submitted Cookies

CSRF Protection using Synchronizer Tokens

Use of DispatcherServlet in Spring MVC Framework

Agile Methodology – Know the What and How?