Activity:
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)
Development Process
- Create custom validation rule
- Add validation rule to Customer class
- Display error message on HTML form
- Update confirmation page
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:
In this initialize method, we can get actual prefix of value and that value will be stored in a variable “coursePrefix“.
At this point our validator is up and running and now someone can use it. By using boolean method.
Lets start coding our activity
Create a new @Annotation
// 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: