How to use @Pattern on non-mandatory fields JSR 303

Erhan Bagdemir picture Erhan Bagdemir · May 14, 2011 · Viewed 15.4k times · Source

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

Answer

BalusC picture BalusC · May 14, 2011

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.