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

Share this article

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

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.

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.

Frequently Asked Questions (FAQs) about Java Bean Validations

What is the purpose of Java Bean Validation?

Java Bean Validation is a framework that allows developers to ensure that the objects in their applications meet certain criteria. This is done through the use of annotations, which can be applied to fields, methods, and classes. The validation rules are defined in a declarative way, which means that they are specified directly in the code, rather than being written in a separate configuration file. This makes the code easier to read and maintain.

How does the validateProperty method work in Java Bean Validation?

The validateProperty method is used to validate a specific property of a Java Bean. It takes two parameters: the object to be validated and the name of the property. The method returns a set of ConstraintViolation objects, which represent the validation errors. If the set is empty, it means that the property is valid.

How does the validateValue method work in Java Bean Validation?

The validateValue method is similar to validateProperty, but instead of validating a property of an object, it validates a standalone value. This method is useful when you want to validate a value before assigning it to a property. Like validateProperty, it returns a set of ConstraintViolation objects.

What is the difference between validateProperty and validateValue?

The main difference between these two methods is that validateProperty validates a property of an object, while validateValue validates a standalone value. This means that validateProperty needs an instance of the object, while validateValue does not.

How can I customize the validation messages in Java Bean Validation?

You can customize the validation messages by using the message attribute of the validation annotations. The message attribute takes a string, which can be a literal message or a key to a message in a resource bundle. If it’s a key, the actual message will be retrieved from the resource bundle at runtime.

Can I use Java Bean Validation with other frameworks?

Yes, Java Bean Validation can be used with other frameworks, such as Spring and Hibernate. These frameworks provide integration with Java Bean Validation, which allows you to use the validation annotations in your Spring or Hibernate entities.

Can I create my own validation annotations in Java Bean Validation?

Yes, you can create your own validation annotations in Java Bean Validation. This is done by creating a new annotation and a corresponding ConstraintValidator. The ConstraintValidator defines the logic of the validation.

How can I handle validation errors in Java Bean Validation?

Validation errors are represented by ConstraintViolation objects. You can get the details of the errors from these objects, such as the invalid value, the validation message, and the path to the invalid property. You can then handle the errors as you see fit, for example, by displaying the validation messages to the user.

Can I validate multiple properties at once in Java Bean Validation?

Yes, you can validate multiple properties at once by calling the validate method on the Validator. This method validates all the properties of an object and returns a set of ConstraintViolation objects for all the invalid properties.

Can I disable a validation rule in Java Bean Validation?

Yes, you can disable a validation rule by using the groups attribute of the validation annotations. By default, all validation rules are in the Default group. If you want to disable a rule, you can put it in a different group and then validate the object without that group.

Alejandro GervasioAlejandro Gervasio
View Author

Alejandro Gervasio is a senior System Analyst from Argentina who has been involved in software development since the mid-80's. He has more than 12 years of experience in PHP development, 10 years in Java Programming, Object-Oriented Design, and most of the client-side technologies available out there.

nicolaipquick-tipvalidation
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week
Loading form