Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7445399
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 29, 20262026-05-29T11:48:39+00:00 2026-05-29T11:48:39+00:00

As stated in the title I can’t make the error message for the FieldMatchValidator

  • 0

As stated in the title I can’t make the error message for the FieldMatchValidator to show in my freemarker template. All the other “regular” error messages, such as @NotNull are displayed with the accurate message from message.properties. The validation with FieldMatchValidator works since the result.hasErrors() returns true and the result objects holds the FieldMatch error. What have I missed?

applicationContext.xml:

<!-- Invokes Spring MVC @Controller methods -->
    <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
        <property name="webBindingInitializer">
            <!-- Configures Spring MVC DataBinder instances -->
            <bean class="org.springframework.web.bind.support.ConfigurableWebBindingInitializer">
                <property name="validator" ref="validator"/>
            </bean>
        </property>
    </bean>


    <bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
        <property name="messageInterpolator">
            <bean class="com.reco.web.mvc.validator.CustomMessageInterpolator">
                <property name="messageSource" ref="messageSource"/>
            </bean>
        </property>
    </bean>

Controller:

@Controller
public class RegisterController extends MyWebController{

    private static final String REGISTER_FORM_VIEW = "/action/register/register";
    private static final String REGISTER_SUCCESS_VIEW = "/action/register/success";

    private org.springframework.validation.Validator validator;

    @Autowired
    public RegisterController(MessageSource messageSource, Validator validator) {
        super(messageSource);
        this.validator = validator;
    }

    @InitBinder
    protected void initBinder(WebDataBinder binder) {
        binder.setValidator((org.springframework.validation.Validator)validator);
    }

    @RequestMapping(value = "/action/register", method = RequestMethod.GET)
    public ModelAndView getRegisterForm() {
        ModelAndView mav = new ModelAndView(REGISTER_FORM_VIEW);
        mav.addObject("registerForm", new RegisterForm());
        return mav;
    }

    @RequestMapping(value = "/action/register", method = RequestMethod.POST)
    public final String register(@Valid RegisterForm registerForm, BindingResult result, ModelMap model, HttpServletRequest request) {

        if (result.hasErrors()) {
            return REGISTER_FORM_VIEW;
        }

        return "redirect:" + REGISTER_SUCCESS_VIEW;
    }


}

Annotation:

@Target({TYPE, ANNOTATION_TYPE})
@Retention(RUNTIME)
@Constraint(validatedBy = FieldMatchValidator.class)
@Documented
public @interface FieldMatch {

    String message() default "{constraints.fieldmatch}";

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

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

    /**
     * @return The first field
     */
    String first();

    /**
     * @return The second field
     */
    String second();

    /**
     * Defines several <code>@FieldMatch</code> annotations on the same element
     *
     * @see FieldMatch
     */
    @Target({TYPE, ANNOTATION_TYPE})
    @Retention(RUNTIME)
    @Documented
            @interface List {
        FieldMatch[] value();
    }


}

Validator:

public class FieldMatchValidator implements ConstraintValidator<FieldMatch, Object>
{
    private String firstFieldName;
    private String secondFieldName;

    @Override

public void initialize(final FieldMatch constraintAnnotation)
{
    firstFieldName = constraintAnnotation.first();
    secondFieldName = constraintAnnotation.second();        

}



   @Override
    public boolean isValid(final Object value, final ConstraintValidatorContext context)
    {
        try
        {
            final Object firstObj = BeanUtils.getProperty(value, firstFieldName);
            final Object secondObj = BeanUtils.getProperty(value, secondFieldName);

            return firstObj == null && secondObj == null || firstObj != null && firstObj.equals(secondObj);
        }
        catch (final Exception ignore)
        {
            // ignore
        }
        return true;
    }
}

freemarker template:

<!doctype html>
<html lang="sv">
<head>
    <meta charset="utf-8"/>
    <title></title>
</head>
<body id="register">

<div id="content">
    <form id="registerForm" action="${rc.contextPath}/action/register" method="POST">
        <p>
            <label for="firstname">firstname</label>
        <@spring.formInput "registerForm.firstName" />
        <@spring.showErrors "", "error"/>
        </p>

        <p>
            <label for="lastname">lastname</label>
        <@spring.formInput "registerForm.lastName" />
        <@spring.showErrors "", "error"/>
        </p>

        <p>
            <label for="email">email</label>
        <@spring.formInput "registerForm.email" />
        <@spring.showErrors "", "error"/>
        </p>

        <p>
            <label for="email_again">email_again</label>
        <@spring.formInput "registerForm.confirmEmail" />
        <@spring.showErrors "", "error"/>
        </p>

        <p>
            <label for="password">password</label>
        <@spring.formPasswordInput "registerForm.password" />
        <@spring.showErrors "", "error"/>
        </p>

        <p>
            <label for="password_again">password_again</label>
        <@spring.formPasswordInput "registerForm.confirmPassword" />
        <@spring.showErrors "", "error"/>
        <@spring.showErrors "", "confirmPassword"/>
        </p>

        <input type="submit"/>
    </form>

</div>

</body>
</html>

FormObject:

@FieldMatch.List({
        @FieldMatch(first = "password", second = "confirmPassword", message = "validation.message.confirm.password"),
        @FieldMatch(first = "email", second = "confirmEmail", message = "validation.message.confirm.email")
})
public class RegisterForm implements Serializable {

    private static final int MAX_TEXT_FIELD_SIZE = 32;

    /**
     * Password min size.
     */
    private static final int PASSWORD_MIN_SIZE = 8;

    /**
     * Password max size.
     */
    private static final int PASSWORD_MAX_SIZE = 36;

    @NotNull(message = "validation.message.firstname.empty")
    @Size(min = 1, max = MAX_TEXT_FIELD_SIZE, message = "validation.message.firstname.length")
    @Pattern(regexp = "^[^<>]*$", message = "validation.message.invalid.characters")
    private String firstName;

    @NotNull(message = "validation.message.lastname.empty")
    @Size(min = 1, max = MAX_TEXT_FIELD_SIZE, message = "validation.message.lastname.length")
    @Pattern(regexp = "^[^<>]*$", message = "validation.message.invalid.characters")
    private String lastName;

    @NotNull(message = "validation.message.email.empty")
    @Pattern(regexp = ".+@.+\\.[a-z]+", message = "validation.message.email", flags = { Pattern.Flag.CASE_INSENSITIVE })
    private String email;

    @NotNull(message = "validation.message.email.empty")
    @Pattern(regexp = ".+@.+\\.[a-z]+", message = "validation.message.email", flags = { Pattern.Flag.CASE_INSENSITIVE })
    private String confirmEmail;

    @NotNull
    @Size(min = PASSWORD_MIN_SIZE, max = PASSWORD_MAX_SIZE)
    private String password;

    @NotNull
    @Size(min = PASSWORD_MIN_SIZE, max = PASSWORD_MAX_SIZE)
    private String confirmPassword;

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getConfirmEmail() {
        return confirmEmail;
    }

    public void setConfirmEmail(String confirmEmail) {
        this.confirmEmail = confirmEmail;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getConfirmPassword() {
        return confirmPassword;
    }

    public void setConfirmPassword(String confirmPassword) {
        this.confirmPassword = confirmPassword;
    }
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-29T11:48:40+00:00Added an answer on May 29, 2026 at 11:48 am

    I solved the problem by adding the proper constraint validation message:

    errorMessage = constraintAnnotation.message();
    

    to the proper field inside the custom FieldMatchValidator. In my case I added the error to the second field:

    context.buildConstraintViolationWithTemplate(errorMessage).addNode(secondFieldName).addConstraintViolation();
    

    FieldMatchValidator

    public class FieldMatchValidator implements ConstraintValidator<FieldMatch, Object>
    {
        private String firstFieldName;
        private String secondFieldName;
        private String errorMessage;
    
        @Override
        public void initialize(final FieldMatch constraintAnnotation)
        {
            firstFieldName = constraintAnnotation.first();
            secondFieldName = constraintAnnotation.second();
            errorMessage = constraintAnnotation.message();
    
        }
    
        @Override
        public boolean isValid(final Object value, final ConstraintValidatorContext context)
        {
            try
            {
                final Object firstObj = BeanUtils.getProperty(value, firstFieldName);
                final Object secondObj = BeanUtils.getProperty(value, secondFieldName);
    
                boolean valid = firstObj == null && secondObj == null || firstObj != null && firstObj.equals(secondObj);
    
                if(!valid){
                    context.buildConstraintViolationWithTemplate(errorMessage).addNode(secondFieldName).addConstraintViolation();
                }
    
                return valid;
            }
            catch (final Exception ignore)
            {
                // ignore
            }
            return true;
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Can someone explain why this causes the error stated in the title? CGFloat dx
I've googled the error (stated in the Question title) and can't find anything relevant.
As stated in the title, how can I modify - in the simplest manner
As the title states, how can i get a temp directory acessible by all
As stated in the title, is there a way, using regular expressions, to match
I have the following VBA code and I am getting the error message stated
Simple as the title states: Can you use only Java commands to take a
As stated in the title, i'm looking for an XML schema (XSD-file) for the
As stated in the title, I need double shortcut keys for my application (ie.
as stated in the title.

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.