@Size(min,max)但不是必需的 [英] @Size(min, max) but not required
问题描述
嗨在我的春季网络应用程序中,我有一个密码变量,我想要至少0个字符或大于6个字符且小于20个。我知道有注释:
Hi In my spring webapp I have a password variable which I want to be at least 0 characters or more than 6 and less than 20. I know that there is annotation:
@Size(min=6, max=20)
<但是我不知道如何增加密码可以是0个字符的可能性。有人会帮我吗?
but I have no idea how to add possibility that password can be 0 characters. Will somebody help me with this?
推荐答案
鉴于评论,您可以使用 StringTrimmerEditor一个
将空字符串转换为null,然后 @Size
check将不会触发(null在@Size中被视为有效)。
Given the comment, you can use StringTrimmerEditor
to convert empty string to null, and then @Size
check will not trigger (null is considered as valid in @Size).
在你的控制器中添加以下方法:
In your controller add following method:
@InitBinder
public void initBinder(WebDataBinder binder) {
binder.registerCustomEditor(String.class, new StringTrimmerEditor(true));
}
请注意 StringTrimmerEditor
还修剪了空格的输入,如果你只想让一个属性受到这个编辑器的影响,可以使用 registerCustomEditor(类<?> requiredType,String propertyPath,PropertyEditor propertyEditor)
。
Note that StringTrimmerEditor
also trims input from spaces, and if you only want one property to be affected by this editor use registerCustomEditor(Class<?> requiredType, String propertyPath, PropertyEditor propertyEditor)
.
这篇关于@Size(min,max)但不是必需的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!