Spring MVC form validation: how to make a field optional?

I have a form (Spring 3 MVC project) and I use DTO (data transfer object) to validate the data. Data is sent to the controller, and I verify its validity using the BindingResult.hasErrors() method and corresponding annotations. I'm going to simplify here, as I have a problem with numeric fields.

DTO:

 public class Item { private String discount; @Digits(integer = 15, fraction = 2) public String getDiscount() { return discount; } } 

If I submit the form without anything written in the discount field, BindingResult.hasErrors() will return true with a message

numeric value out of bounds (<15 digits>.<2 digits> expected) .

What I want to do is that the discount field may be empty, but if something is written in it, it should be in the number format provided by the @Digits annotation. How can i do this?

+4
source share
2 answers

What you need to do is configure Spring to convert the empty string to null . You can achieve this by registering a StringTrimmerEditor in the FormController initBinder method:

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

StringTrimmerEditor

Then, as defined by parsifal, @Digits consider null as valide.

+5
source

You can create your own validation annotation. An explanation can be found in the spring documentation: http://static.springsource.org/spring/docs/3.0.0.RC3/reference/html/ch05s07.html , par 5.7.2.2

-1
source

All Articles