MVC 1.0 in Java EE 8 - Handling Form Validation Errors

3 min read
This blogpost of my MVC 1.0 series is a about Handling Form Validation Errors. It uses the snippets from the last post where handling form inputs in general is explained. In addition to that, this post adds form validation and its handling on top of the handling form inputs post.


Handling Form Input 

There are two ways to handle form inputs in MVC controllers. The simplest way is to use @FormParam annotation map the form input to MVC controller method parameters. The second one is to aggregate multiple with @FormParam annotated parameters as a single object.
This case is shown in the following snippet:
The Person parameter of this addOwner method is a simple Java Pojo with two @FormParam annotations. The Strings within these annotations have to match with the HTML input form.










 Adding Validations

Because of the Bean Validation integration in MVC, adding form validations to input fields is pretty easy. In this concrete example the Person class has to be annotated with the prefered validation. In the following snippet a check for non-empty input fields is added.












Validation annotations like @Size, @NotNull and so on can either be added to the respective properties or even parameters.
In case you need validations different from the standard javax.validation ones you should take a look at Hibernate Validator by Red Hat which is available here.

Note: Empty input fields result in empty String parameters and not in nullvalued parameters.

After adding validation annotations to the Person input class, the controller and the addOwner() controller method have to be changed.
The first step is to inject the javax.mvc.binding.BindingResult class as a property in the controller class.
The second step is to add error handling to the controller method. This can be done by using the injected BindingResult reference.



Handling validation errors has to be done with an if-condition which checks if the BindingResult contains errors by calling the isFailed() method. If a property (for example the firstname) is empty the BindingResult reference contains the corresponding errors, messages and so on. These properties can be used to fill an error bean and redirect to an error page for example.

Conclusion

Handling form validations in MVC 1.0 is pretty simple. The respective properties have to be annotated with validation annotations. In addition to that the controller which handles the form input and the possible errors needs to contain an injected BindingResult reference which has to be used to handle validation errors.


Bye,
Bennet


Be Social, Share!