0

Similar question is posted here-> Spring + Thymeleaf custom validation display but I could not figure out the solution so posting this new question. I have a simple registration form having username,email, password and confirmPassword fields

<form action="#" th:action="@{/register}" th:object="${user}"
method=post>

<!--error detection start  -->
<div class="alert alert-danger" th:if="${#fields.hasErrors('*')}">
    <p th:each="err : ${#fields.errors('*')}" th:text="${err}"></p>
</div>
<!--error detection ends  -->
<div class="form-group input-group">
    <div class="input-group-prepend">
        <span class="input-group-text"> <i class="fa fa-user"></i>
        </span>
    </div>
    <input name="username" th:field="*{username}" class="form-control"
        placeholder="User Name" type="text">
</div>
<div class="form-group input-group"
    th:if="${#fields.hasErrors('username')}" th:errors="*{username}">Name
    Error</div>

<!-- form-group// -->
<div class="form-group input-group">
    <div class="input-group-prepend">
        <span class="input-group-text"> <i class="fa fa-envelope"></i>
        </span>
    </div>
    <input name="email" th:field="*{email}" class="form-control"
        placeholder="Email address" type="email">
</div>
<div class="form-group input-group"
    th:if="${#fields.hasErrors('email')}" th:errors="*{email}">Name
    Error</div>

<div class="form-group input-group">
    <div class="input-group-prepend">
        <span class="input-group-text"> <i class="fa fa-lock"></i>
        </span>
    </div>
    <input class="form-control" th:field="*{password}"
        placeholder="Create password" type="password">
</div>
<!-- form-group// -->
<div class="form-group input-group">
    <div class="input-group-prepend">
        <span class="input-group-text"> <i class="fa fa-lock"></i>
        </span>
    </div>
    <input class="form-control" th:field="*{confirmPassword}"
        placeholder="Repeat password" type="password">
    <p class="error-message"
        th:each="error: ${#fields.errors('user.confirmPassword')}"
        th:text="${error}">Validation error</p>
</div>
<!-- form-group// -->
<div class="form-group">
    <button type="submit" class="btn btn-primary btn-block">
        Create Account</button>
</div>
<!-- form-group// -->
<p class="text-center">
    Have an account? <a href="">Log In</a>
</p>
</form>

I added a custom validation which gets trigger when password and confirm password field do not match.

1.FieldsValueMatchValidator

public class FieldsValueMatchValidator implements ConstraintValidator<FieldsValueMatch, Object> {

private String field;
private String fieldMatch;

public void initialize(FieldsValueMatch constraintAnnotation) {
    this.field = constraintAnnotation.field();
    this.fieldMatch = constraintAnnotation.fieldMatch();
}

public boolean isValid(Object value, ConstraintValidatorContext context) {

    Object fieldValue = new BeanWrapperImpl(value).getPropertyValue(field);
    Object fieldMatchValue = new BeanWrapperImpl(value).getPropertyValue(fieldMatch);

    if (fieldValue != null) {
        return fieldValue.equals(fieldMatchValue);
    } else {
        return fieldMatchValue == null;
    }

}

}

3.FieldsValueMatch

@Constraint(validatedBy = FieldsValueMatchValidator.class)
@Target({ ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
public @interface FieldsValueMatch {

String message() default "Fields values don't match!";

Class<?>[] groups() default {};

Class<? extends Payload>[] payload() default {};

String field();

String fieldMatch();

@Target({ ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@interface List {
    FieldsValueMatch[] value();
}
}

4.User.java

@FieldsValueMatch(field = "password", fieldMatch = "confirmPassword", message = "Passwords do not match!")
@Entity
public class User implements UserDetails
{
    @NotBlank
    private String password;

    @Transient
    @NotBlank
    private String confirmPassword;
        //other getters and setters
}

5.Controller code

@PostMapping("/register")
public String saveNonJsonData(@Valid @ModelAttribute("user") User theUser, BindingResult errors) {
if (errors.hasErrors()) {
    return "register";
}
else
{
//successlogic
}

Custom validator is working fine and i can see the error message on the page using following code on thymeleaf page

<!--error detection start  -->
<div class="alert alert-danger" th:if="${#fields.hasErrors('*')}">
    <p th:each="err : ${#fields.errors('*')}" th:text="${err}"></p>
</div>
<!--error detection ends  -->

As mentioned here - Spring + Thymeleaf custom validation display the problem is custom validator returning an ObjectError for password field match validation and not a fieldError. Even though I tried solution provided I can't figure out how to get Thymeleaf to display my custom error.

UPDATE Got one more answer here Displaying "Passwords don't match" custom annotation message and now i can see the error message using following code

<input class="form-control" th:field="*{confirmPassword}" placeholder="Repeat password" type="password">
<div class="form-group input-group" th:if="${#fields.hasErrors('global')}" th:errors="*{global}"></div>

My updated question if I have two more fields for example 'email' and 'confirmEmail' field then how this approach will work on thymeleaf page?

Phoenix
  • 11
  • 2
  • 9
  • Can you please try the solution from here: https://stackoverflow.com/questions/50785814/spring-class-level-validation-and-thymeleaf You can add a new property node and then in the template map the errors for both password and repeat password fields to this newly created node. – Ioan M Apr 12 '19 at 09:24
  • Yes it worked... Thanks – Phoenix Apr 12 '19 at 17:44

0 Answers0