Get invalid user input with error type Spring typeMismatch
I have implemented a ReloadableResourceBundleMessageSource file in my Spring MVC application that I use to display prettier error messages for binding exceptions. The problem I'm running into is that due to company policy, these errors should be displayed in the following format:
[inputData] is not valid [fieldName].
The field name is available by default in my post properties file (as argument {0}), but I can't figure out how to display invalid user input. Is it possible?
a source to share
Yes,
Error The tag does not allow you to retrieve the "value" provided by your user. See link
Let's assume your errors.properties file goes here (root from classpath file) (note that I only use one argument {0})
// errors.properties
error.invalid=is not a valid {0}
When inspecting your command object, you do the following:
import static org.springframework.validation.ValidationUtils.*;
public boolean validate(Object command, Errors errors) {
Person person = (Person) command;
/**
* new Object [] plays the role of the supplied arguments
*/
rejectIfEmpty(errors, "age", "error.invalid", new Object[] {"Age"}, "Age is required");
/**
* If your label is a resource bundle key, use DefaultMessageSourceResolvable instead
*
* rejectIfEmpty(errors, "age", "error.invalid", new Object[] {new DefaultMessageSourceResolvable("person.age")}, "Age is required");
*/
}
UPDATE
But to achieve your goal, you must provide a custom messageSource ( Notification instead of continue)
public class PolicyMessageSource implements MessageSource {
private ResourceBundleMessageSource resourceBundle;
public PolicyMessageSource() {
resourceBundle = new ResourceBundleMessageSource();
/**
* Suppose your resource bundle is called messages.properties (root of the classpath)
*/
resourceBundle.setBasenames(new String[] {"messages"});
}
public String getMessage(String code, Object[] args, String defaultMessage, Locale locale) {
return resourceBundle.getMessage(code, args, defaultMessage, locale);
}
public String getMessage(String code, Object[] args, Locale locale) throws NoSuchMessageException {
return resourceBundle.getMessage(code, args, locale);
}
public String getMessage(MessageSourceResolvable resolvable, Locale locale) throws NoSuchMessageException {
if(resolvable instanceof FieldError) {
FieldError fieldError = (FieldError) resolvable;
/**
* Here goes what you want
*/
return fieldError.getRejectedValue() + resourceBundle.getMessage(resolvable, locale);
}
return resourceBundle.getMessage(resolvable, locale);
}
}
So, define your PolicyMessageSource as messageSource
<bean id="messageSource" class="br.com.spring.PolicyMessageSource"/>
Remember that you only have to define one messageSource instance called messageSource. Note that I am using ResourceBundleMessageSource . You should check the same approach when using ReloadableResourceBundleMessageSource . Remember this.
a source to share