Java
Article
By Alejandro Gervasio

Java Bean Validation’s validateProperty() and validateValue() in Three Minutes

By Alejandro Gervasio

While it’s not widely known, Java Bean Validation ships with the validateProperty() and validateValue() methods, which can be used for validating the individual fields of a constrained class as well as values even before assigning them.

I assume that you already have at least a basic background on how to use the standard for validating objects, but if you want to get a more intimate understanding on how this works, feel free to check my previous article, where I took an in-depth look at Bean Validation’s core features.

--ADVERTISEMENT--

Selective Validation of Field-Level Constraints

In a typical use case, a constrained domain class like the following will be validated in one single step with a Bean Validation implementation, like Hibernate Validator.

public class User {

    @NotEmpty(message = "Name may not be empty")
    @Size(min = 2, max = 32,
            message = "Name must be between 2 and 32 characters long")
    private String name;

    @NotEmpty(message = "Email may not be empty")
    @Email(message = "Email must be a well-formed email address")
    private String email;

    public User(){}

    public User(String name, String email) {
        this.name = name;
        this.email = email;
    }

    // setters and getters for name / email

}

But with validateProperty() and validateValue() the validation process can be performed more selectively.

The validateProperty() Method

Consider a situation when you just want to validate a specific field of the earlier User class, rather than checking all of them in one pass. In such a case, you may want to use the validateProperty() method, which is called with a constrained object and the name of the bean property to be validated:

User user = new User("", "john@domain.com");
validator
        .validateProperty(user, "name")
        .stream()
        .forEach(violation -> System.out.println(violation.getMessage()))

Here, a constraint violation will be raised because an empty string has been passed as a value for the name field.

Along the same line, the email field could be validated as follows:

User user = new User("", "john@domain.com");
validator
        .validateProperty(user, "email")
        .stream()
        .forEach(violation -> System.out.println(violation.getMessage()))

This would not raise a violation because "john@domain.com" looks like a valid email address. The fact that the name is still empty is irrelevant because the call validateProperty(user, "email") will only validate the email field.

The validateValue() Method

As we just saw, the validateProperty() method makes validating a specific constrained class field a no-brainer. A potential downside of this method is that an instance of the target class must be created and the value assigned to the field, therefore making the whole validation code a little bloated.

To avoid this, the same can be done without having to create such an instance, through the validateValue() method. It is called with the constrained class (the Class itself, not an instance of it), the bean property’s name and the value in question:

validator
         .validateValue(User.class, "name", "")
         .stream()
         .forEach(violation -> System.out.println(violation.getMessage()));

In this case, a constraint violation message will be printed out to the console, considering that the name field does not accept empty strings. As you can see, there’s no need to instantiate the target class.

Pretty much the same can be done with every constrained class field. This shows in a nutshell that Bean Validation can be used for validating the fields of a target class by following a more selective strategy.

Use validateProperty() and validateValue() for instant Java Bean Validation

Summary

As we just learned, a call to validateProperty() with an instance of a constrained class and a specific class’ field name will instruct the validator to check only that field. Calling its counterpart validateValue() with the constrained class (no instance of it is required), a field name and a value will validate the whether the value is valid for that field.

To put it in a simpler way, the heart of the matter of the whole validation process lies in calling these methods with the right arguments. Yes, it’s really that easy.

Of course, validating selectively the field of a class is just the tip of the iceberg when it comes to consuming the Bean Validation API , as the standard packages many other nifty features worth looking. Keep in mind that Java Bean Validation is evolving at pretty fast pace, so make sure to check the official docs and keep up to date with the latest news.

Recommended
Sponsors
Get the latest in Java, once a week, for free.