Spring validation

Option 1- Programmatic validation with Validator interface:

1a) Implement Validator interface:

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

1b) Autowire into Controller

    @Autowired
    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

    @Size(max=64)
    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"
      class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"/>

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

<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-validator</artifactId>
    <version>5.0.1.Final</version>
</dependency>

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

http://static.springsource.org/spring/docs/3.0.5.RELEASE/reference/view.html#view-jsp-formtaglib-errorstag

Reference:

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