Here are the models:
public class myFormData {
private BigDecimal trackingNumber;
@Valid
private List records = new ArrayList();
}
public class myCustomRecord {
//the field also appears here (for child records)
private BigDecimal trackingNumber;
}
I have a controller method which receives this object at some point to do a save.
public @ResponseBody ValidationResponse save(Model model,
@Valid myFormData formData, BindingResult result,
HttpSession session){
//do stuff
}
The problem I'm having is if a string is passed into the trackingNumber field, the error message is not nice.
Failed to convert property value of type 'java.lang.String' to required type 'java.math.BigDecimal' for property 'records[0].trackingNumber'; nested exception is java.lang.NumberFormatException
Failed to convert property value of type 'java.lang.String' to required type 'java.math.BigDecimal' for property 'trackingNumber'; nested exception is java.lang.NumberFormatException
One other potential complication is I'm not using Spring form since I'm trying to do some ajax submissions. This is how I'm submitting the data:
function collectFormData(fields) {
var data = {};
//myFormData
data["trackingNumber"] = <>;
for (var i = 0; i < fields.length; i++) {
data["records["+i+"].trackingNumber"] = <>;
//some more data to submit for child records
}
return data;
}
var mData = collectFormData(aSelectedRows);
if (aSelectedRows.length> 0) {
$.post('call_controller_save', mData, function(response) {
if (response.status === 'FAIL') {
displayError(response);
} else {
//SAVE SUCCESSFUL
$('#successMsgs').append("Data Saved");
}, 'json');
}
I've tried changing trackingNumber's data type to String and wrote a custom ConstraintValidator. It does the trick... I can put in a custom message via ValidationMessages.properties, but I would like to keep the models true to the intended data type. Is there another way to control the error message and turn it into something nice and user friendly?
(I also understand the NumberFormatException is most likely happening in data binding, before the validation step? But I'm still not sure how to go about fixing the default message)
Edit
I use the following configuration
id="messageSource">
messages
ValidationMessages
In each properties file, I have the identical content.
formData.trackingNumber=Invalid format
But the custom message is still not getting picked up. Question 2: Should it be formData or myFormData? I have confusion whether it is the class name or name of the form object used on the jsp page?
解决方案
Add to validation messages - this kind of format is used by default by Spring if it cannot convert from supplied text to number:
typeMismatch.java.math.BigDecimal=Required format is number.