Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bind global errors generated from form validation to specific form fields in spring

Tags:

spring

binding

Is it possible to do that?
I have made a custom annotation that checks if 2 fields are equal from here.
I would like to validate if a field "password" is equal to another field "confirmedPassword". Now if they are not, I'd like the error message to be displayed linked to the confirmedPassword field. I display errors in jsp with <form:errors path="" />. Is there another way to do this? Also there could also be another 2 fields in this annotation email and confirmedEmail. How could I make the distinction between which global error to put where...

I hope it all makes sense..

like image 840
Marius Avatar asked Sep 14 '26 08:09

Marius


1 Answers

This thread from the Hibernate Validator forums seems to indicate that you want to add something like the following code to your custom validator's isValid() method:

https://forum.hibernate.org/viewtopic.php?f=9&t=1003351&view=next

constraintValidatorContext.disableDefaultConstraintViolation();
constraintValidatorContext.buildConstraintViolationWithTemplate( errorMessage ).addNode("confirmPassword").addConstraintViolation();

The .addNode("confirmPassword") bit looks from the docs like it will customize the path of the error:

http://download.oracle.com/javaee/6/api/javax/validation/ConstraintValidatorContext.html#buildConstraintViolationWithTemplate%28java.lang.String%29

Then you should be able to show just the error for confirmPassword by using path="confirmPassword" in your error tag.

like image 183
sdouglass Avatar answered Sep 17 '26 12:09

sdouglass