Jan 3rd, 2013, 10:45 AM
Binding form values to Number fields
We're running into a few issues while attempting to bind a String from a form submission to Long and Integer fields. Looking at PropertyEditor, Converters, and Formatters, none seem to fully solve our issues. When just using the direct default binding, Spring will strip out all whitespace, so while we expect "1 2" to give us an error, it instead becomes 12. Also, Spring is doing hexadecimal conversion, so whereas we would also like to reject "#10" or "0x10", these instead become 16. Specifying a NumberFormatter on the CustomNumberEditor solves the hexadecimal issue but adds another issue where decimal values are rounded instead of being rejected.
The first solution would be to create our own custom PropertyEditor. We would rather have something we could apply on a field by field basis using annotations, but I tried this out anyway. However, some of the fields we would like to left pad with 0's to various lengths when they are displayed back to the user. Again, preferably that would happen with annotations. When using a custom PropertyEditor though, any Formatters attached to the field are being ignored.
If instead going with Converters or Formatters, we run into the same issue with both. Neither will allow us to properly reject a value because any Exception thrown just causes Spring to fallback to the default CustomNumberEditor which in turn brings back all the original issues.
This all seems like it would be a fairly common issue that people would have run into before, but so far I have been unable to find any solutions in my searches. We would like to keep any of this logic server-side. Any suggestions would be greatly appreciated.