Introduction to Jakarta Bean Validation

We are working on a fresh, updated Jakarta EE Tutorial. This section hasn’t yet been updated.

This chapter describes Jakarta Bean Validation available as part of the Jakarta EE platform and the facility for validating objects, object members, methods, and constructors.

Overview of Jakarta Bean Validation

Validating input received from the user to maintain data integrity is an important part of application logic. Validation of data can take place at different layers in even the simplest of applications, as shown in Developing a Simple Facelets Application: The guessnumber-jsf Example Application. The guessnumber-faces example application validates the user input (in the h:inputText tag) for numerical data at the presentation layer and for a valid range of numbers at the business layer.

Jakarta Bean Validation provides a facility for validating objects, object members, methods, and constructors. In Jakarta EE environments, Jakarta Bean Validation integrates with Jakarta EE containers and services to allow developers to easily define and enforce validation constraints. Jakarta Bean Validation is available as part of the Jakarta EE platform.

Using Jakarta Bean Validation Constraints

The Jakarta Bean Validation model is supported by constraints in the form of annotations placed on a field, method, or class of a JavaBeans component, such as a managed bean.

Constraints can be built in or user defined. User-defined constraints are called custom constraints. Several built-in constraints are available in the jakarta.validation.constraints package. Built-In Jakarta Bean Validation Constraints lists all the built-in constraints. See Creating Custom Constraints for information on creating custom constraints.

Built-In Jakarta Bean Validation Constraints
Constraint Description Example

@AssertFalse

The value of the field or property must be false.

@AssertFalse
boolean isUnsupported;

@AssertTrue

The value of the field or property must be true.

@AssertTrue
boolean isActive;

@DecimalMax

The value of the field or property must be a decimal value lower than or equal to the number in the value element.

@DecimalMax("30.00")
BigDecimal discount;

@DecimalMin

The value of the field or property must be a decimal value greater than or equal to the number in the value element.

@DecimalMin("5.00")
BigDecimal discount;

@Digits

The value of the field or property must be a number within a specified range. The integer element specifies the maximum integral digits for the number, and the fraction element specifies the maximum fractional digits for the number.

@Digits(integer=6, fraction=2)
BigDecimal price;

@Email

The value of the field or property must be a valid email address.

@Email
String emailaddress;

@Future

The value of the field or property must be a date in the future.

@Future
Date eventDate;

@FutureOrPresent

TThe value of the field or property must be a date or time in present or future.

@FutureOrPresent
Time travelTime;

@Max

The value of the field or property must be an integer value lower than or equal to the number in the value element.

@Max(10)
int quantity;

@Min

The value of the field or property must be an integer value greater than or equal to the number in the value element.

@Min(5)
int quantity;

@Negative

The value of the field or property must be a negative number.

@Negative
int basementFloor;

@NegativeOrZero

The value of the field or property must be negative or zero.

@NegativeOrZero
int debtValue;

@NotBlank

The value of the field or property must contain atleast one non-white space character.

@NotBlank
String message;

@NotEmpty

The value of the field or property must not be empty. The length of the characters or array, and the size of a collection or map are evaluated.

@NotEmpty
String message;;

@NotNull

The value of the field or property must not be null.

@NotNull
String username;

@Null

The value of the field or property must be null.

@Null
String unusedString;

@Past

The value of the field or property must be a date in the past.

@Past
Date birthday;

@PastOrPresent

The value of the field or property must be a date or time in the past or present.

@PastOrPresent
Date travelDate;

@Pattern

The value of the field or property must match the regular expression defined in the regexp element.

@Pattern(regexp="\\(\\d{3}\\)\\d{3}-\\d{4}")
String phoneNumber;

@Positive

The value of the field or property must be a positive number.

@Positive
BigDecimal area;

@PositiveOrZero

The value of the field or property must be a positive number or zero.

@PositiveOrZero
int totalGoals;

@Size

The size of the field or property is evaluated and must match the specified boundaries. If the field or property is a String, the size of the string is evaluated. If the field or property is a Collection, the size of the Collection is evaluated. If the field or property is a Map, the size of the Map is evaluated. If the field or property is an array, the size of the array is evaluated. Use one of the optional max or min elements to specify the boundaries.

@Size(min=2, max=240)
String briefMessage;

In the following example, a constraint is placed on a field using the built-in @NotNull constraint:

public class Name {
    @NotNull
    private String firstname;

    @NotNull
    private String lastname;
    ...
}

You can also place more than one constraint on a single JavaBeans component object. For example, you can place an additional constraint for size of field on the firstname and the lastname fields:

public class Name {
    @NotNull
    @Size(min=1, max=16)
    private String firstname;

    @NotNull
    @Size(min=1, max=16)
    private String lastname;
    ...
}

The following example shows a method with a user-defined constraint that checks user-defined constraint that checks for a predefined phone number pattern, such as a country specific phone number:

@USPhoneNumber
public String getPhone() {
    return phone;
}

For a built-in constraint, a default implementation is available. A user-defined or custom constraint needs a validation implementation. In the preceding example, the @USPhoneNumber custom constraint needs an implementation class.

Repeating Annotations

From Bean Validation 2.0 onwards, you can specify the same constraint several times on a validation target using repeating annotation:

public class Account {

    @Max (value = 2000, groups = Default.class, message = "max.value")
    @Max (value = 5000, groups = GoldCustomer.class, message = "max.value")
    private long withdrawalAmount;
}

All in-built constraints from jakarta.validation.constraints package support repeatable annotations. Similarly, custom constraints can use @Repeatable annotation. In the following sample, depending on whether the group is PeakHour or NonPeakHour, the car instance is validated as either two passengers or three passengers based car, and then listed as eligible in the car pool lane:

/**
 * Validate whether a car is eligible for car pool lane
 */
@Documented
@Constraint(validatedBy = CarPoolValidator.class)
@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE })
@Retention(RUNTIME)
@Repeatable(List.class)
public @interface CarPool {

    String message() default "{CarPool.message}";

    Class<?>[] groups() default {};

    int value();

    Class<? extends Payload>[] payload() default {};

    /**
     * Defines several @CarPool annotations on the same element
     * @see (@link CarPool}
     */
    @Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE })
    @Retention(RUNTIME)
    @Documented
    @interface List {
        CarPool[] value();
    }
}
public class Car{

  private String registrationNumber;

  @CarPool(value = 2, group = NonPeakHour.class)
  @CarPool(value = 3, group = {Default.class, PeakHour.class})
  private int totalPassengers;
}

Any validation failures are gracefully handled and can be displayed by the h:messages tag.

Any managed bean that contains Bean Validation annotations automatically gets validation constraints placed on the fields on a Jakarta Faces application’s web pages.

For more information on using validation constraints, see the following:

Validating Null and Empty Strings

The Java programming language distinguishes between null and empty strings. An empty string is a string instance of zero length, whereas a null string has no value at all.

An empty string is represented as "". It is a character sequence of zero characters. A null string is represented by null. It can be described as the absence of a string instance.

Managed bean elements represented as a Jakarta Faces text component such as inputText are initialized with the value of the empty string by the Jakarta Faces implementation. Validating these strings can be an issue when user input for such fields is not required. Consider the following example, in which the string testString is a bean variable that will be set using input entered by the user. In this case, the user input for the field is not required.

if (testString==null) {
    doSomething();
} else {
    doAnotherThing();
}

By default, the doAnotherThing method is called even when the user enters no data, because the testString element has been initialized with the value of an empty string.

In order for the Bean Validation model to work as intended, you must set the context parameter jakarta.faces.INTERPRET_EMPTY_STRING_SUBMITTED_VALUES_AS_NULL to true in the web deployment descriptor file, web.xml:

<context-param>
    <param-name>jakarta.faces.INTERPRET_EMPTY_STRING_SUBMITTED_VALUES_AS_NULL</param-name>
    <param-value>true</param-value>
</context-param>

This parameter enables the Jakarta Faces implementation to treat empty strings as null.

Suppose, on the other hand, that you have a @NotNull constraint on an element, meaning that input is required. In this case, an empty string will pass this validation constraint. However, if you set the context parameter jakarta.faces.INTERPRET_EMPTY_STRING_SUBMITTED_VALUES_AS_NULL to true, the value of the managed bean attribute is passed to the Jakarta Bean Validation runtime as a null value, causing the @NotNull constraint to fail.

Validating Constructors and Methods

Jakarta Bean Validation constraints may be placed on the parameters of nonstatic methods and constructors and on the return values of nonstatic methods. Static methods and constructors will not be validated.

public class Employee {
...
  public Employee (@NotNull String name) { ... }

  public void setSalary(
      @NotNull
      @Digits(integer=6, fraction=2) BigDecimal salary,
      @NotNull
      @ValidCurrency
      String currencyType) {
    ...
  }
...
}

In this example, the Employee class has a constructor constraint requiring a name and has two sets of method parameter constraints. The amount of the salary for the employee must not be null, cannot be greater than six digits to the left of the decimal point, and cannot have more than two digits to the right of the decimal place. The currency type must not be null and is validated using a custom constraint.

If you add method constraints to classes in an object hierarchy, special care must be taken to avoid unintended behavior by subtypes. See Using Method Constraints in Type Hierarchies for more information.

Cross-Parameter Constraints

Constraints that apply to multiple parameters are called cross-parameter constraints, and may be applied at the method or constructor level.

@ConsistentPhoneParameters
@NotNull
public Employee (String name, String officePhone, String mobilePhone) {
  ...
}

In this example, a custom cross-parameter constraint, @ConsistentPhoneParameters, validates that the format of the phone numbers passed into the constructor match. The @NotNull constraint applies to all the parameters in the constructor.

Cross-parameter constraint annotations are applied directly to the method or constructor. Return value constraints are also applied directly to the method or constructor. To avoid confusion as to where the constraint applies, parameter or return value, choose a name for any custom constraints that identifies where the constraint applies. For instance, the preceding example applies a custom constraint, @ConsistentPhoneParameters, that indicates that it applies to the parameters of the method or constructor.

When you create a custom constraint that applies to both method parameters and return values, the validationAppliesTo element of the constraint annotation may be set to ConstraintTarget.RETURN_VALUE or ConstraintTarget.PARAMETERS to explicitly set the target of the validation constraint.

Validating Type Arguments of Parameterized Types

From Bean Validation 2.0 onwards, you can apply constraints to the type arguments of parameterized types. For example: List<@NotNull Long> numbers; Constraints can be applied to elements of container types such as List, Map, Optional, and others.

List<@Email String> emails;
public Map<@NotNull String, @USPhoneNumber String> getAddressesByType() { }

In this sample, @Email is an in-built constraint supported by Bean Validation, and @USPhoneNumber is a user-defined constraint. See Using the Built-In Constraints to Make a New Constraint.

@USPhoneNumber has ElementType.TYPE_USE as one of its @Target, and therefore it is possible to use @USPhoneNumber constraint for validating type arguments of parameterized types.

Identifying Parameter Constraint Violations

If a ConstraintViolationException occurs during a method call, the Bean Validation runtime returns a parameter index to identify which parameter caused the constraint violation. The parameter index is in the form argPARAMETER_INDEX, where PARAMETER_INDEX is an integer that starts at 0 for the first parameter of the method or constructor.

Adding Constraints to Method Return Values

To validate the return value for a method, you can apply constraints directly to the method or constructor declaration.

@NotNull
public Employee getEmployee() { ... }

Cross-parameter constraints are also applied at the method level. Custom constraints that could be applied to both the return value and the method parameters have an ambiguous constraint target. To avoid this ambiguity, add a validationAppliesTo element to the constraint annotation definition with the default set to either ConstraintTarget.RETURN_VALUE or ConstraintTarget.PARAMETERS to explicitly set the target of the validation constraint.

@Manager(validationAppliesTo=ConstraintTarget.RETURN_VALUE)
public Employee getManager(Employee employee) { ... }

See Removing Ambiguity in Constraint Targets for more information.

Further Information about Jakarta Bean Validation

For more information on Jakarta Bean Validation, see