@Size (min, max) but not required

Hi In my spring webapp, I have a password variable in which I want to be at least 0 characters or more than 6 and less than 20. I know there is an annotation:

 @Size(min=6, max=20)

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

+6
source share
4 answers

Given a comment, you can use to convert an empty string to zero, and then the check will not start (null is considered valid in @Size). StringTrimmerEditor@Size

In the controller, add the following method:

@InitBinder
public void initBinder(WebDataBinder binder) {
    binder.registerCustomEditor(String.class, new StringTrimmerEditor(true));
}

, StringTrimmerEditor StringTrimmerEditor , , , registerCustomEditor(Class<?> requiredType, String propertyPath, PropertyEditor propertyEditor).

+6

, ("") 6 20 , , @Pattern:

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

, , min = 6 max = 20. @Size, @Size , null.

"", .

+1

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

+1
source

All Articles