如何在非强制性字段上使用@Pattern JSR 303 [英] How to use @Pattern on non-mandatory fields JSR 303

查看:306
本文介绍了如何在非强制性字段上使用@Pattern JSR 303的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在非强制性表单字段上使用@Pattern约束?

How can i use @Pattern constraint on non-mandatory form fields ?

@Pattern(regexp="...")
private String something;

我提交表单后,会立即收到验证错误,但用户可能会将该字段留空,因为这不是必填字段.

as soon as i submit my form, i get validation error as expected but the user may leave the field empty, since this is not a mandatory field.

PS:我可以编写自己的约束注释.但是,我只是问一个结合注释或添加注释属性的简便方法. JSR303的实现是休眠验证器.

PS: i could write my own constraint annotation. However, i just ask an easier way combining annotations or adding annotation attributes. JSR303 implementation is hibernate-validator.

推荐答案

只需使用null而不是空字符串进行设置即可.由于默认情况下,空的HTML输入字段作为空字符串作为HTTP请求参数提交,因此您需要让MVC框架将空的提交值解释为null.在JSF中,这可以通过web.xml中的<context-param>轻松完成.但是,由于您使用的是Spring MVC,但我没有这样做,所以我在这里搜索了一下,发现

Just set it with null instead of empty string. Since empty HTML input fields are by default submitted as an empty string as HTTP request parameter, you need to let your MVC framework interpret empty submitted values as null. This is in JSF easy done by a <context-param> in web.xml. However, since you're using Spring MVC and I don't do it, I searched a bit here and found this answer which may be of use.

这篇关于如何在非强制性字段上使用@Pattern JSR 303的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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