@Size(min, max) but not required

家住魔仙堡 提交于 2019-12-07 02:46:52

问题


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)

but I have no idea how to add possibility that password can be 0 characters. Will somebody help me with this?


回答1:


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));
}

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).




回答2:


If you want a String which is either empty ("") or between 6 and 20 characters long, you could specify a regular expression using the @Pattern constraint:

@Pattern(regexp="(^$|.{6,20})")



回答3:


You can use ConstraintComposition, at least in Hibernate Validator 5.




回答4:


I think you want a nullable field, but that also could be min = 6 and max = 20. AFAIK, @Size should only activate if the field is non-null.

If you're sending an empty string "", it will be validated.



来源:https://stackoverflow.com/questions/11550324/sizemin-max-but-not-required

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!