Spring MVC表单验证:如何使字段可选? [英] Spring MVC form validation: how to make field optional?

查看:148
本文介绍了Spring MVC表单验证:如何使字段可选?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表单(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));
}

StringTrimmerEditor

然后由parsifal指定,@Digitsnull值视为有效值.

Then as specified by parsifal, @Digits consider null value as valide.

这篇关于Spring MVC表单验证:如何使字段可选?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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