Home > Articles > Web Development

Java Data Validation Using Hibernate Validator

  • Print
  • + Share This
Online attackers grow more ingenious, with their exploits becoming more audacious and potentially more lucrative. We say crime doesn't pay, and yet the aggregated scale of online crime puts attackers' revenues at around the GDP equivalent of a large country. As software professionals, we have a duty to fight these attackers, and the means to do it in our arsenal of software tools and techniques. One key technique is data validation, which can filter out all kinds of nasty data. Stephen B. Morris explores Java-based validation with some examples using Hibernate Validator.
Like this article? We recommend

Like this article? We recommend

Data validation is a key element of programming. Have you ever written code that runs just fine on simple test data, but falls over when you run it against production data? The cause is often unexpected characters in data, such as attempting to parse character data into an integer object. An example of this simple issue is illustrated in this type of unprotected Java code:

int anInt = Integer.parseInt(input);

Why is this bad? Well, for one thing it lacks a try-catch block, putting the code entirely at the mercy of the input data stream. Here's an improved version:

int anInt = 0;
try {
    anInt = Integer.parseInt(input);
} catch(NumberFormatException e){
     System.out.println("Exception: " + e.printStackTrace();

At least now the non-integer data is kept from entering the program. Just throwing an exception like this is still a bit clunky, because your code must then recover after being dumped into the catch clause. Recovery issues include resource deallocation (closing files, sockets, database connections, and so on).

An improved approach is to use a service style, in which all incoming data is passed into an external validator of some sort. This separation helps to cleanse the data comprehensively, and it avoids the common problem of adding validation code all over the application, which can make your application code cluttered and hard to understand, leading to coding errors.

What would be the major parts of such an external validator? Typically the elements of a validator can consist of a series of tests built against a set of constraints that are run against the data. Here's one simple test (based on the earlier Java code) to verify whether a given string can be parsed into an integer. The constraint in this case is that the supplied data must be numeric and parseable:

public boolean isThisParseable(String input) {
    boolean parseable = true;
    try {
    } catch(NumberFormatException e) {
        parseable = false;
    return parseable;

If the code above returns true, we can safely parse the incoming string, happy in the knowledge that we won't get an exception in our application code. Of course, many other validation tests are possible; for example, here's one for checking the length of a string:

public boolean checkLength(String input, int limit) {
    return input.length() > limit;

This code will verify whether the incoming string length is within a predefined size range. You might think that this type of test is a little over the top! However, in recent years, a well-publicized denial-of-service (DOS) vulnerability was found in Django-based websites where users were allowed to supply unlimited-length passwords. [1] By supplying huge passwords, the attackers were able to tie up the host in processing the login. This Django vulnerability has been fixed, but it's an embarrassing experience for the developers to fall afoul of this type of issue. DOS attacks can result in significant loss of business as well as end-user confidence.

Cross-Site Scripting (XSS) Defense

Cross-Site Scripting (XSS) is a dreaded attack method used extensively against websites. Among other exploits, XSS typically allows an attacker to gain unauthorized access to user- or administrative-level privileges. A common launch method for this type of attack involves getting scripts to run without the user's knowledge, such as by embedding a JavaScript script tag in an HTTP message.

Let's assume that your Java validation code is aware of this trick and strips out any unauthorized tags such as <script>. Remember that I mentioned the attackers' ingenuity? An attacker can potentially get around your validation code by submitting something like this:


When the first (inner) script tag is stripped out, the outer script tag is ready to do its nefarious work. (See Iron-Clad Java: Building Secure Web Applications, by James Manico and August Detlefsen, [1] for much more on this topic.)

Many attackers nowadays are well funded, patient, and often highly skilled. It's useful to remember the first rule of chess: Never underestimate your opponent!

HTTP Messages and Trust in Web Apps

An important rule: Never trust HTTP messages, which can easily be modified in transit. This is another reason why validation is so important in all levels of a web application. (Manico and Detlefsen's brilliant book [1] provides a great deal of advice on this and on many related topics.)

Data Contours

An important part of data validation might be described as understanding the "contours" of the data. This technique helps in preparing for the types of data heading for your code. We'll see this approach in action a bit later, in the discussion of Hibernate Validator constraints.

Service-Based Validation

When you think about it, a service-based validation facility is an example of the Separation of Concerns design pattern. Separation of Concerns is one of the keys to successful development because typically it breaks down a complicated problem into a series of simpler problems. This is also the case for service-based validation, and it applies to the areas of authentication and authorization. It's usually a good idea to implement authentication and authorization as external services, rather than coding them directly into your application. As with validation, this technique keeps your application code clean.

Enough preamble! Let's look at a framework for validation.

Practical Defense with Hibernate Validator

Hibernate Validator allows you to express validation rules in a concise way and then execute those rules. The result is a simple set of pass-fail status values. Why is a framework such a good idea? Isn't it better to just write your own? A framework gives you all the smarts of the authors, without having to reinvent the wheel yourself.

One of the simple examples from the Hibernate Validator site is as follows:

public class Car {

   private String manufacturer;

   @Size(min = 2, max = 14)
   private String licensePlate;

   private int seatCount;

   // ...

Notice the simple annotations, such as @NotNull and @Size(min = 2, max = 14). These annotations represent the rule set for the required validation. What's nice in this case is that the rules are brought right into the core of the data model. Also, the validation facilities are not tied to any particular layer of our web application, allowing us to use Hibernate Validator at the data access layer, the business layer, or the presentation layer.

Why is multi-layer validation a good practice? Imagine if one layer of your application is compromised. With validation at every layer, you have some protection against the data that flows through the other uncompromised layers.

Setting Up Hibernate Validator

Hibernate Validator's setup is pretty straightforward—just follow the directions. You can install the required dependencies using Maven (or Apache Ivy) or by direct JAR file download, whichever you prefer.

To make it easier for readers to run the code, I used an Eclipse-based Maven project. This has the merit of automatically downloading the required dependencies. The dependencies from the pom.xml file I used are as follows:


In terms of dependencies, Hibernate Validator might be a little more suited to a Java EE environment rather than Java SE. However, for the latter, if you don't mind a few additional dependencies (such as the JBoss logging component), Hibernate Validator may be a good fit for you. In any case, the above pom.xml file should get you started.

A More Complete Hibernate Validator Example

Let's use some code based on one of the examples from the Hibernate Validator website (for brevity, I've listed only one of the setter and getter methods):

public class Car {

    private String maker;

    @Size(min = 2, max = 14)
    private String registrationPlate;

    private int seatCount;

    public Car(String maker, String registrationPlate, int seatCount) {
        this.maker = maker;
        this.registrationPlate = registrationPlate;
        this.seatCount = seatCount;

    public String getMaker() {
        return maker;

    public void setMaker(String maker) {
        this.maker = maker;

As discussed earlier, the @NotNull, @Size, and @Min annotations declare the required data-validation constraints. These constraints will be applied directly to the fields of a Car instance in this example, and are composed of the following:

  • The maker must not be null.
  • The registrationPlate must not be null.
  • The registrationPlate must be between 2 and 14 characters in length.
  • The seatCount must be at least 2.

Of course, many more possibilities are available for validation. For example, constraints can be applied to properties (such as getter methods) or even at the class level, making this a pretty flexible tool.

Let's see how to create and run the validator.

Creating a Validator Instance

The easiest way to create a validator instance is via the factory class:

ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();

Once you have a validator instance, it's easy to call the methods and run your rules via validator.validate() against the supplied object:

Car car = new Car(null, true);
Set<ConstraintViolation<Car>> constraintViolations = validator.validate( car );
assertEquals( 1, constraintViolations.size() );
assertEquals( "may not be null", constraintViolations.iterator().next().getMessage() );

Just a few lines of code, and your objects are validated! The results of the validation are all contained inside the constraintViolations set. To view the details, you can just iterate over the set. By this means, your validation requirements boil down to simply defining constraints and then just running a validator instance. That's a lot of power for a small amount of work. This design also buys you more time for application coding, adding security, testing, and so on.

Additional Constraints

In addition to the constraints defined by the Bean Validation API, Hibernate Validator provides several useful custom constraints. For example:


This is a big value-add for the framework, because coding things like Luhn Checksum tests yourself can be very time-consuming. This constraint just helps you to check for format correctness of a supplied credit card number. A few other useful custom constraints:

  • @Email
  • @NotEmpty
  • @URL
  • @SafeHtmlData model validation

Why use validation at the data model level? Good question! Given the fact that web applications are browser-based, there is arguably limited scope for securely storing data on the client side. Data can be stored on the client, it's not a great idea. A better approach is to move the validated data into a secure server-side repository as soon as possible.

All of this is just a way of saying that modern web applications are data-centric. Everything tends to revolve around the database. In some ways, this is a testament to the original database pioneers! Regardless of the type of back-end database (relational, NoSQL, object-oriented, graph, and others), the lightweight browser front-end application tends to rely heavily on the server-side data storage facilities.

For this reason (because of the data-centric element), applying the Hibernate Validator constraints to the data model itself makes sense. It's not mandatory, but it is pretty convenient.


Good data validation is a textbook example of a non-functional requirement. Not getting validation right can result in brittle code that throws exceptions or fails when presented with unexpected data. That's a good scenario. Poor validation can also result in insecure code that acts as an attack launchpad. Data validation is a key skill in the battle against online attackers.

Less well-documented are attackers who operate from inside an organization, such as disgruntled employees. Again, good validation and other standard security practices can help to keep systems secure from this special type of attacker.

Writing your own validation code is not easy. It's time-consuming and can result in gaping holes, such as the one in Django that allowed unbounded-length passwords. All of these issues make a good case for using open-source validation tools such as Hibernate Validator.

Applying validation at the data-model level is both convenient and natural; it gives data modelers and data architects the chance to build validation infrastructure at the same time as (or shortly after) data model creation. One thing to remember with data-model validation is to make sure that your data model is used faithfully at all layers of your application. Used in this way, your validation infrastructure will be available whenever you need it.


[1] James Manico and August Detlefsen, Iron-Clad Java: Building Secure Web Applications." McGraw Hill, 2014.

[2] Stephen B. Morris, Five Steps To Better Multi-language Programming: Simplicity in Multi-language Coding: C/C++, Java, Bash, and Python. Amazon Digital Services, Inc., 2014.

  • + Share This
  • 🔖 Save To Your Account