davioooh
davioooh

Reputation: 24706

Spring form validation for plain HTML form

I need to validate some simple forms in my application. In these forms I have one or two input text to validate so I'd like to not create a specific ModelAttribute class for every form. I'd like to use instead plain HTML form and use @RequestParam annotations to handle POST parameters.

Is there a way to use Spring form validation in this situation (without using model attribute) or should I implement a backing-form object and a validator for each form?

Upvotes: 4

Views: 1322

Answers (5)

Markus W Mahlberg
Markus W Mahlberg

Reputation: 20703

You could instantiate a model object, fill it with the data from the plain form and validate that object programmatically.

Upvotes: 0

geoand
geoand

Reputation: 64039

Currently it is not possible to use @Valid on individual @RequestParam, @PathVariable etc. to trigger validation. This is the relevant feature request on the Spring Issue Tracker. Let's cross our fingers for Spring 4.1!

In your case, you will either have to use @ModelAttribute, or perform custom validation inside the controller (or maybe a Spring interceptor if you want the same validation to apply to multiple endpoints)

Upvotes: 3

Jeevan Mysore
Jeevan Mysore

Reputation: 255

Without a model attribute, Spring form Validation is not possible. Because Spring Form Validation depends on Spring Form Binding, which is a linkage between form elements and Model Attribute. So how small the form may be, create a DTO(Model Attribute), bind it to form and Perform Validations.

Upvotes: 1

codependent
codependent

Reputation: 24472

Definitely not possible using Spring's validation API (Errors object):

java.lang.IllegalStateException: An Errors/BindingResult argument is expected to be declared immediately after the model attribute, the @RequestBody or the @RequestPart arguments to which they apply

Upvotes: 0

Andromed
Andromed

Reputation: 31

I think you can do this with Annotation. You can specifie for your parameters annotation like :

  • @Size(min=3, max=5)
  • @NotNull
  • @NotEmpty

...

Upvotes: 1

Related Questions