Spring CustomNumberEditor解析不是数字的数字 [英] Spring CustomNumberEditor parses numbers that are not numbers

查看:1578
本文介绍了Spring CustomNumberEditor解析不是数字的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 ......那么数字是10,没有错误

  • number = 10a .....那么数字是10,没有错误

  • number = 10a25 ......那么数字是10,没有错误

  • number = a ......错误,因为数字无效

  • 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

所以看起来,编辑器解析该值,直到它可以省略其余的。有没有办法配置这个编辑器,所以验证是严格的(所以数字如10a或10a25导致错误),或者我必须构建我的自定义实现。我在CustomDateEditor / DateFormat中看起来像设置宽松为false,所以日期不能被解析为最可能的。

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.

我注册编辑器的方式是: p>

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));
}

谢谢。

推荐答案

由于它依赖于NumberFormat类,它停止解析第一个无效字符的输入字符串,我想你将不得不扩展NumberFormat类。

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.

首先脸红将是

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
}

这篇关于Spring CustomNumberEditor解析不是数字的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆