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
![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](https://kvttechlead.home.blog/wp-content/uploads/2020/12/image-3.png?w=678)
// 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](https://kvttechlead.home.blog/wp-content/uploads/2020/12/image.png?w=471)