Today I am going to write about how to use Javax/Hibernate validation. Most of us encountered a problem where we had to check input data (e.g
POST endpoint) has necessary values before processing it. In most cases, you would have used hibernate validation or something similar for this. This blog post however is targeted for developers who validates these values in their code.
You need following dependencies on your pom.xml
Now let’s take a look at the
As you can see, the
Person has fields name, age and voted. By using the annotation
@NotNull we are saying these fields are required and must not be null. Additionally for name, we also have
@Pattern annotation which specifies the name cannot be empty String as well as cannot composed of only white spaces too.
We are going to implement a new class called
In the constructor of this class, we are instantiating an
ObjectMapper and setting the configuration such that when parsing a reader (data) if there are any unknown fields, then
UnrecognizedPropertyException is thrown. We are also instantiating a new validator. The private method
validate will take a Person instance and validates these fields. If there is Set of
ConstraintViolation, the method throws
run and test
I have implemented this
ParseMain class to test the validation. As you can see from the
unrecognised variable, the String contains a field called surname which cannot be mapped to a field in Person class.
In the second String we are missing a field voted and the name doesn’t match the pattern.
In my first
catch statement, I am catching an
IOException and simply logging the exception. In the second
catch statement, I am catching the
ConstraintViolationException and then populating the
Map<String,String> map using
ConstraintViolation#getPropertyPath() as key and
ConstraintViolation#getMessage() as value. I then log this map.
When we run this main method, following stack trace is printed out.
Javax validation is very useful library especially when you want to validate an input content. All in all this library gets a thumbs up from me.
PS: I’ve written the demo code in a hurry so please excuse the code quality 😉
If you enjoyed the read, drop us a comment below or share the article, follow us on Twitter or subscribe to our #MetaBeers newsletter. Before you go, grab a PDF of the article, and let us know if it’s time we worked together.