@Size(min, max) but not required

假如想象 提交于 2019-12-05 07:08:51

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

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

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

Jonathan S. Fisher

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.

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