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

Nginx

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

Use @Initbinder in Spring MVC

How to read Dates with Hibernate

CSRF Protection using Synchronizer Tokens

CSRF Protection using Double Submitted Cookies

Add Logging Messages in Spring 5.1 - All Java Config Version

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

Hibernate and Primary Keys