Search code examples
javaspringdata-bindingspring-mvcpropertyeditor

Spring CustomNumberEditor parses numbers that are not numbers


I'm using Spring CustomNumberEditor editor to bind my float values and I've experimented that if in the value is not a number sometimes it can parse the value and no error is returned.

  • number=10 ...... then the number is 10 and there's no errors
  • number=10a ...... then the number is 10 and there's no errors
  • number=10a25 ...... then the number is 10 and there's no errors
  • number=a ...... error because the number is not valid

So it seems that the editor parses the value until it can and omit the rest. Is there any way to configure this editor so the validation is strict (so numbers like 10a or 10a25 result in error) or do I have to build my custom implementation. I'm looking something like setting lenient to false in CustomDateEditor/DateFormat so dates cannot be parsed to the most probable one.

The way I register the editor is:

@InitBinder
public void initBinder(WebDataBinder binder){
    NumberFormat numberFormat = NumberFormat.getInstance();
    numberFormat.setGroupingUsed(false);
    binder.registerCustomEditor(Float.class, new CustomNumberEditor(Float.class, numberFormat, true));
}

Thanks.


Solution

  • Since it relies on the NumberFormat class, which stops parsing the input string at the first invalid character I think you'll have to extend the NumberFormat class.

    First blush would be

    public class StrictFloatNumberFormat extends NumberFormat {
    
      private void validate(in) throws ParseException{
         try {
           new Float(in);
         }
         catch (NumberFormatException nfe) {
           throw new ParseException(nfe.getMessage(), 0);     
      }
    
    
      public Number parse(String in) throws ParseException {
        validate(in);
        super.parse(in);
      }
      ..... //any other methods
    }