0

i'm trying to get a well-formatted validation error message from message resource.

Expected: username can't be empty What I get: can't be empty. validation_en.properties :

NotEmpty=can't be empty

messages_en.properties

username=Username

My Class

    @Value
public class LoginForm{
    @NotEmpty
    private final String username;
...

Configuration Class:

    @Configuration
public class WebAdaptorConfiguration implements WebMvcConfigurer {
    @Bean
    public MessageSource messageSource() {
        ResourceBundleMessageSource resource =
                new ResourceBundleMessageSource();
        resource.setBasenames("messages","validation");
        resource.setDefaultEncoding("utf-8");
        return resource;
    }

    @Bean
    public LocaleResolver localeResolver() {
        SessionLocaleResolver sessionLocaleResolver = new SessionLocaleResolver();
        sessionLocaleResolver.setDefaultLocale(new Locale("fa"));
        return sessionLocaleResolver;
    }
    @Bean
    public LocalValidatorFactoryBean getValidator() {
        LocalValidatorFactoryBean bean = new LocalValidatorFactoryBean();
        bean.setValidationMessageSource(messageSource());
        return bean;
    }

}

View:

<label th:if="${#fields.hasErrors('username')}" th:errors="*{username}"
                        class="validation-message"></label>

1 Answer 1

0

You've specified the default message for the @NotEmpty constraint to always be 'can't be empty'.

In order to use your custom message for the @NotEmpty constraint specifically validating the username field in your LoginForm, you need to follow the message property naming convention:

Constraint.formName.propertyName

So in your case, the message property for your username property becomes NotEmpty.loginForm.username=username can't be empty

I couldn't find any reference to that convention in the Hibernate validator docs or Spring docs but this article also explains it - https://www.codejava.net/frameworks/spring/spring-mvc-form-validation-example-with-bean-validation-api

Sign up to request clarification or add additional context in comments.

2 Comments

I want to avoid this kind of redundancy,if i have n fields and m error types with my way i should write n+m lines but as you say it becomes n*m
You're right, it certainly would become repetitive. Unfortunately, to my knowledge at least, it has to be like that in order narrow it down to a specific form, which was your original question. Now, you do have the option of making it so all @NotEmpty validated username fields can have the same validation message: NotEmpty.username=username can't be empty

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.