Spring CustomNumberEditor解析不是数字的数字


问题内容

我正在使用Spring
CustomNumberEditor编辑器来绑定我的float值,并且我已经尝试过,如果在值中不是数字,则有时它可以解析该值并且不返回错误。

  • number = 10 ......则数字为10,没有错误
  • number = 10a ......则数字为10,没有错误
  • number = 10a25 ......那么数字是10并且没有错误
  • number = a ......错误,因为该数字无效

因此,似乎编辑器会解析该值,直到可以并忽略其余值为止。有什么方法可以配置此编辑器,以便验证严格(例如10a或10a25之类的数字会导致错误),还是我必须构建自己的自定义实现。我正在寻找类似在CustomDateEditor
/ DateFormat中将lenient设置为false的方法,因此日期无法解析为最可能的日期。

我注册编辑器的方式是:

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

谢谢。


问题答案:

由于它依赖于NumberFormat类,该类将停止在第一个无效字符处解析输入字符串,所以我认为您必须扩展NumberFormat类。

首先脸红是

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
}