Spring MVC表单验证:如何使字段可选? [英] Spring MVC form validation: how to make field optional?
问题描述
我有一个表单(Spring 3 MVC项目),并且我正在使用DTO(数据传输对象)进行数据验证.数据被发送到控制器,我正在使用BindingResult.hasErrors()
方法和适当的注释检查其有效性.我将在此处进行简化,因为我在使用数字字段时遇到了问题.
I have a form (Spring 3 MVC project) and I'm using DTO (data transfer object) for data validation. Data is sent to a controller and I'm checking for it's validity with BindingResult.hasErrors()
method and appropriate annotations. I'm going to simplify here since I'm having a problem with numeric fields.
DTO:
public class Item {
private String discount;
@Digits(integer = 15, fraction = 2)
public String getDiscount() {
return discount;
}
}
如果我提交的表单中未在discount
字段中写任何内容,则BindingResult.hasErrors()
将返回true并显示消息
If I submit form with nothing written in discount
field, BindingResult.hasErrors()
will return true with message
numeric value out of bounds (<15 digits>.<2 digits> expected)
.
我要完成的是discount
字段可以为空,但是如果在其中写入内容,则应采用@Digits
批注提供的数字格式.我该怎么办?
What I want to accomplish is that discount
field can be empty but if something is written in it it should be in numerical format provided by @Digits
annotation. How can I do that?
推荐答案
您需要配置Spring,以将空字符串转换为空.您可以通过在FormController initBinder
方法中注册StringTrimmerEditor
来实现此目的:
What you need to do is configuring Spring to convert empty String to null. You can achieve this by registering a StringTrimmerEditor
in your FormController initBinder
method :
@InitBinder
public void initBinder(WebDataBinder binder) {
binder.registerCustomEditor(String.class, new StringTrimmerEditor(true));
}
然后由parsifal指定,@Digits
将null
值视为有效值.
Then as specified by parsifal, @Digits
consider null
value as valide.
这篇关于Spring MVC表单验证:如何使字段可选?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!