Spring CustomNumberEditor 解析非数字的数字
我正在使用 Spring CustomNumberEditor 编辑器来绑定浮点值,并且我已经尝试过,如果值不是数字,有时它可以解析该值并且不会返回错误。
- 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));
}
谢谢。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你不能用 NumberFormat 来做到这一点。
文档清楚地说明了这一事实:
当您接受此 API 时,编写一个执行您想要的操作并实现 NumberFormat 接口的解析器甚至是无效的。这意味着您必须实现自己的属性编辑器。
You can not do this whith NumberFormat.
The documentation is clear about this fact:
When you acceept this API it would even be even invalid to write a parser that does what you want and implement the NumberFormat interface. This mean you have to implment your own Property Editor instead.
由于它依赖于 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.
First blush would be
我认为最优雅的方法是使用 NumberFormat.parse(String,ParsePosition) ,如下所示:
I think the most elegant approach would be to use
NumberFormat.parse(String,ParsePosition)
, something like this: