Dropwizard validation example


In this tutorial, we will see about Dropwizard validation example.

As discussed in the previous dropwizard tutorial, hibernate validator is packaged with Dropwizard, so whatever validations you can put with hibernate validator, you can do same with Dropwizard as well.

Resource endpoint validation

You can validate almost anything at resource end point.

Let’s take a quick example.

Constraining entities

You can put various validations at entity level. I will extend same example which I have provided in dropwizard tutorial.
Let’s annotate book class to apply the following constraints.

  • Title must not be null or “Dummy”
  • Number of pages in book should be greater than 10 and less than 1000.

@ValidationMethod is dropwizard annotation and isNotDummy method should return true for book entity to be valid.
Let’s put @Valid in post and put request in BookController class.

As you can see, we have annotation @valid with post and put request.
Let’s start DropwizardApplication.java again and test out application using postman.
Post method is used to create new resource. Here we are adding new Book “Effective Javascript” to book list, so you can see we have used new book json in post body.
URL: “localhost:8080/bookService/books”.
As you can see, we have put number of pages as 3 which is lesser than 10, so we are getting error here.
Another post request:
URL: “localhost:8080/bookService/books”.

Validated method
As we have provided title as “Dummy” in our post request body,isNotDummy will return false and our entity will not be a valid one.

Source code

Download source code – Dropwizard validation example

That’s all about Dropwizard validation example.


Join Our News Letter – Stay Updated

Subscribe to Awesome Java Content.

Add Comment

Join Our News Letter - Stay Updated

Subscribe to Awesome Java Content.
You can like our facebook page Java2blog