Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Mvc -- custom validation message for typeMismatch

I have a field that requires a double. If you enter a String, the default message is something like:

Failed to convert property value of type java.lang.String to required type java.lang.Double for property price; nested exception is java.lang.NumberFormatException: For input string: "fsd"

A custom message for when the value is not entered. I've set this message doing the following:

@NotNull(message = "price is required")
private Double price;

Is there an equivalent annotation for type mismatch?

like image 438
user2892437 Avatar asked May 19 '17 14:05

user2892437


2 Answers

There is no validation annotation for type mismatch because that happens during data binding, and if data binding for a field fails then validation won't take place. But if you want to change the message that appears in the errors list, you should be able to do that using the messages.properties file in your project's resource bundle. I use the following key in my messages file which works for me for joda-time date fields:

typeMismatch.org.joda.time.LocalDate=Dates must be entered in the format MM/DD/YYYY

See this question for more information.

like image 199
some_stacker Avatar answered Oct 06 '22 18:10

some_stacker


There is no simple way. In fact validation cannot be applied. Validation is applied to initialized POJO. in your case the POJO cannot be created there is no valid value to initialize Double.

As a workaround in one of my projects we make all POJO fields Strings and validate them. Also methods to convert the String values to Double/Boolean/Date etc. were provided.

like image 5
StanislavL Avatar answered Oct 06 '22 18:10

StanislavL