Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override error messages in BindingResult

I am using Spring MVC 2.5 .

I have fields where numbers should only be the allowed in put. And I get the exact error message on my UI I was looking for . Something like

Failed to convert property value of type [java.lang.String] to required type [java.math.BigDecimal] for property executionThresholdAmount; nested exception is java.lang.NumberFormatException

I don't want to display that kind of message to the user. I do use message.properties file to organize texts to be displayed.

The only thing I need is I wanted to overwrite the error message for specific fields. I couldn't do that but here is the trick I was using for

if(result.hasFieldErrors()){

            List<FieldError> bindingErrors=( List<FieldError>)result.getFieldErrors();
            BindingResult fieldErrors=new BeanPropertyBindingResult (offerSetting, "offerSetting");
            for(FieldError error :bindingErrors ){
                String field=error.getField();                
                fieldErrors.rejectValue(field, "invalid.amount."+field);


            }


            result=fieldErrors;
            #more code

What I am doing is I created BeanPropertyBindingResult which is an implementation of BindingResult and populated the error fields with the message I want and pass the reference to result object so it gets displayed. However, I am now getting both the default messages

like

Failed to convert property value of type [java.lang.String] to required type [java.math.BigDecimal] for property executionThresholdAmount; nested exception is java.lang.NumberFormatException

and also the message I wanted. Something like

"The amount for field price you entered is invalid"

Any better ideas?

like image 925
WowBow Avatar asked Dec 05 '25 07:12

WowBow


1 Answers

Try adding to your messages properties file somethig like this:

typeMismatch.objectClassName.field=Your custom message

In your case:

typeMismatch.offerSetting.amount=The amount for field price you entered is invalid

Works for me :)

like image 92
jelies Avatar answered Dec 06 '25 20:12

jelies