Spring validation

Option 1- Programmatic validation with Validator interface:

1a) Implement Validator interface:

  • org.springframework.validation.Validator
    • supports(…)
    • validate(…)

1b) Autowire into Controller

    private UserValidator validator;

1c) Invoke validate() method

validator.validate(user, result); // option 1
// option 2 - set inside a @InitBinder method
binder.setValidator(...) // .validate() will get called automatically

1d) Test for errors:

if (result.hasErrors()){ ... }

Option 2 – Declarative validation

2a) Annotate class

    private String name;

2b) Annotate @Controller parameter input with @Valid.

    public void doSomething(@Valid SomeForm form, BindingResults result)

2d) Bootstrap the Bean Validator implementation (only necessary if working outside MVC):

<bean id="validator"

2e) Provide a Validator interface (ex: Hibernate Validations) in classpath.


Display errors:

Finally if using JSP, display the errors in view with error tags from Spring-Form:

<form:errors path="firstName" />
<!-- path="*" to show errors for all fields -->



Posted in Spring

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: