How to get the Invalid value in the error message while using custom validator in spring?

若如初见. 提交于 2019-12-04 07:02:41

问题


I having trouble in showing Invalid value in the error message I have messages.properties file as follows

ProductId.exists.custom.validator.validation = A product already exists with product id ${validatedValue}.

and following is my custom validtor interface

@Target( { METHOD, FIELD, ANNOTATION_TYPE })
@Retention(RUNTIME)
@Constraint(validatedBy = ProductIdValidator.class)
@Documented
public @interface ProductId {
   String message() default "{ProductId.exists.custom.validator.validation}";

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

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

Here is the implementation

@Component
public class ProductIdValidator implements ConstraintValidator<ProductId, String>{

    @Autowired
    private ProductService productService;

    @Override
    public void initialize(ProductId constraintAnnotation) {
        // TODO Auto-generated method stub
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        Product product = productService.getProductById(value);
        if(product!= null) {
            return false;
        }
        return true;
    }

}

When I am running my application I am getting error message like A product already exists with product id ${validatedValue}. but I am expecting A product already exists with product id P1234. as error message

How to get the validatedValue in error message?

Additional details I have used hibernate-validator:4.3.1.Final version and spring-webmvc:3.2.0.RELEASE And I am triggering the validation in the context as follows

<mvc:annotation-driven validator="validator"/>
<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
    <property name="validationMessageSource" ref="messageSource" />
</bean>

回答1:


I’m not sure what was the main reason for this solution I’ve used in my project – if to make interpolation work, or just use ReloadableResourceBundleMessageSource (that supports properties in UTF-8 and runtime reloading!) instead of the default one. However, this should work for you.

<mvc:annotation-driven validator="validator" />

<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean" primary="true"
      p:messageInterpolator-ref="messageInterpolator" />

<!-- Hibernate Validator which can interpolate the value being validated in the constraint message -->
<bean id="messageInterpolator" class="ValueFormatterMessageInterpolatorFactoryBean"
      p:messageSource-ref="validatorMessageSource" />

<bean id="validatorMessageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource"
      p:basename="classpath:/config/i18n/validator-messages"
      p:defaultEncoding="utf-8"
      p:cacheSeconds="0" />

And the custom ValueFormatterMessageInterpolatorFactoryBean class:

/**
 * {@linkplain FactoryBean} that creates {@link ValueFormatterMessageInterpolator}
 * with underlying {@link ResourceBundleMessageInterpolator} that uses the given
 * {@link MessageSource}.
 */
public class ValueFormatterMessageInterpolatorFactoryBean implements FactoryBean<MessageInterpolator> {

    private MessageSource messageSource;

    public MessageInterpolator getObject() throws Exception {
        ResourceBundleLocator resourceBundleLocator = new MessageSourceResourceBundleLocator(messageSource);
        return new ValueFormatterMessageInterpolator(
                new ResourceBundleMessageInterpolator(resourceBundleLocator));
    }

    public Class<?> getObjectType() {
        return ValueFormatterMessageInterpolator.class;
    }

    public boolean isSingleton() {
        return true;
    }

    @Required
    public void setMessageSource(MessageSource messageSource) {
        this.messageSource = messageSource;
    }
}

Note: I’m using Hibernate Validator 4.3.0.Final.



来源:https://stackoverflow.com/questions/20146689/how-to-get-the-invalid-value-in-the-error-message-while-using-custom-validator-i

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!