【问题标题】:Validation Error format in spring boot with Message Resource使用消息资源的 Spring Boot 中的验证错误格式
【发布时间】:2020-07-09 13:43:15
【问题描述】:

我正在尝试从消息资源中获取格式正确的验证错误消息。

预期:用户名不能为空 我得到的:不能为空。 验证_en.properties:

NotEmpty=can't be empty

messages_en.properties

username=Username

我的班级

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

配置类:

    @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;
    }

}

查看:

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

【问题讨论】:

    标签: spring-boot validation


    【解决方案1】:

    您已将@NotEmpty 约束的默认消息指定为始终为“不能为空”。

    为了将您的自定义消息用于@NotEmpty 约束,专门验证您的LoginForm 中的username 字段,您需要遵循消息属性命名约定:

    约束.formName.propertyName

    因此,在您的情况下,username 属性的 message 属性变为 NotEmpty.loginForm.username=username can't be empty

    我在 Hibernate 验证器文档或 Spring 文档中找不到对该约定的任何引用,但本文也解释了它 - https://www.codejava.net/frameworks/spring/spring-mvc-form-validation-example-with-bean-validation-api

    【讨论】:

    • 我想避免这种冗余,如果我有 n 个字段和 m 个错误类型,我应该写 n+m 行,但正如你所说,它变成 n*m
    • 你是对的,它肯定会变得重复。不幸的是,至少据我所知,它必须是这样才能将其缩小到特定的形式,这是您最初的问题。现在,您可以选择让所有@NotEmpty 验证的username 字段都可以具有相同的验证消息:NotEmpty.username=username can't be empty
    猜你喜欢
    • 2017-12-28
    • 2022-01-09
    • 2019-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-27
    • 2018-01-23
    相关资源
    最近更新 更多