In our previous post, we discussed how to use Java bean validation (AKA JSR-303 or Jakarta Bean Validation) in your Spring Boot and Java applications. We also discussed in a separate post, how to use bean validation to validate REST API calls.
However, we only introduced a very small subset of the constraints that are available from the bean validation library.
In this post, we will present a comprehensive list of constraints that are available from the Java bean validation library. For each constraint, we will summarize it’s function and behavior so that you could have a broad understanding of what the JSR-303 specification provides.
We will divide the available constraints into different groups, based on the functionality provided by the constraint. Please keep in mind that this grouping is our own and does not come from the JSR-303 specification.
Null/NotNull constraints
In this group, we will present constraints that apply on the value of a variable’s reference. These constraints
Constraint name | Constraint condition | Applicable data types | Example |
---|---|---|---|
@NotNull | The annotated item is considered valid if it does not have a null value. | Can be added to an item of any type. Has no effect on items of a primitive data type. | @NotNull Object something; |
@Null | The annotated item is considered valid if it has a null value. | Same as @NotNull. Can be added to an item of any type. Has no effect on items of a primitive data type. | @Null String value; |
AssertTrue/AssertFalse
In this group, we will present constraints that can be applied to boolean data types.
Constraint name | Constraint condition | Applicable data types | Example |
---|---|---|---|
@AssertTrue | The annotated item is considered valid, if it has the value true. Null objects automatically considered valid. | boolean and the wrapper Boolean. | @AssertTrue boolean isImportant; |
@AssertFalse | The annotated item is considered valid, if it has the value false. Null objects automatically considered valid. | boolean and the wrapper Boolean. | @AssertFalse Boolean isExpired; |
Min/Max constraints
In this section, we will present constraints that you can apply on numerical data types to enforce minimum and maximum values.
Please keep in mind that these constraints do not support the data types double, float and their respective wrappers. This is due to potential rounding errors.
Also note that the following annotations consider null values as valid.
Constraint name | Constraint condition | Applicable data types | Example |
---|---|---|---|
@Min | Constraint is fulfilled if the annotated value is equal to or greater than the specified integer value. | BigDecimal, BigInteger, byte, short, int, long, Byte, Short, Integer, Long. | @Min(33) int x; |
@Max | Constraint is fulfilled if the annotated value is smaller than or equal to the specified integer value. | BigDecimal, BigInteger, byte, short, int, long, Byte, Short, Integer, Long. | @Max(2000) Long y; |
@DecimalMin | Annotated item must be equal to or larger than the specified decimal value. The decimal value is specified by a String. See example. | CharSequence, BigDecimal, BigInteger, byte, short, int, long, Byte, Short, Integer, Long. | @DecimalMin(“33.42”) BigDecimal myValue; |
@DecimalMax | Annotated item must be equal to or smaller than the specified decimal value. The decimal value is specified by a String. See example. | CharSequence, BigDecimal, BigInteger, byte, short, int, long, Byte, Short, Integer, Long. | @DecimalMax(“133.42”) String myValueAsString; |
Negative/Positive value constraints
JSR-303 also provides constraints which can be used to enforce rules on numerical values such that values can only be positive or negative.
Note that these constraints will consider annotated items as valid if they have a null value.
Constraint name | Constraint condition | Applicable data types | Example |
---|---|---|---|
@Negative | Item must have a negative value. 0 is considered invalid. | BigDecimal, BigInteger, byte, short, int, long, float, double and their wrappers (Long, Double, etc..). | @Negative int x; |
@Postive | Item must have a positive value. 0 is considered invalid. | BigDecimal, BigInteger, byte, short, int, long, float, double and their wrappers (Long, Double, etc..). | @Postive Long y; |
@NegativeOrZero | Item must have a negative value. 0 is considered valid. | BigDecimal, BigInteger, byte, short, int, long, float, double and their wrappers (Long, Double, etc..). | @NegativeOrZero double z; |
@PostiveOrZero | Item must have a positive value. 0 is considered valid. | BigDecimal, BigInteger, byte, short, int, long, float, double and their wrappers (Long, Double, etc..). | @PostiveOrZero Float myVal; |
The Digits constraint
The @Digits constraint is a special JSR-303 constraint which can be applied to numerical values to enforce a specific number of integer and fraction digits. In the constraint declaration, one can define the maximum number of integer digits and the maximum number of fractional digits a value can have.
Integer and fractional digits can be explained with the following example:
12345.6789
Integer digits . fractional digits
In the example above, the number has 5 integer digits and 4 fractional digits.
An example usage of this constraint can be found below:
public void myTestFunction(@Digits(integer = 10, fraction = 2) BigDecimal myValue){
Examples of valid values for this constraint are “23.4”, “33”, “-1234567.44”. Invalid values can be “12345123451” or “22.345”.
Please note that the constraint considers null values as valid.
The constraint supports the following data types:
- BigDecimal
- BigInteger
- CharSequence (such as String)
- byte, short, int, long
- Byte, Short, Integer, Long
Email and Pattern constraints
The @Email and @Pattern constraints can be used to enforce a specific pattern on String values. These constraints consider null values as valid.
Constraint name | Constraint condition | Applicable data types | Example |
---|---|---|---|
String value has to be a correctly formatted email address. You can also add a regular expression which will be used as an additional check in the constraint. This can be useful in cases such as when requiring email addresses from a specific domain or a specific country. | CharSequence | @Email(regexp = “.*\\.co.uk$”) String ukEmail; @Email String anyEmail; | |
@Pattern | String value must match the given regular expression. The annotation can be configured with one or more flags to modify the behavior of the validation. For example, to perform case-insensitive pattern matching, or to enable multi-line mode. | CharSequence | @Pattern (regexp = “.*\\.co.uk$”) String ukDomain; @Pattern (regexp = “.*\\.co.uk$”, flags = Pattern.Flag.CASE_INSENSITIVE) String ukDomainCI |
Future/Past constraints
The following constraints can be applied on objects which represent a date and time value. These constraints can be used to make sure values are in the past, present or the future.
The following data types are supported:
- java.util.Date
- java.util.Calendar
- java.time.Instant
- java.time.LocalDate
- java.time.LocalDateTime
- java.time.LocalTime
- java.time.MonthDay
- java.time.OffsetDateTime
- java.time.OffsetTime
- java.time.Year
- java.time.YearMonth
- java.time.ZonedDateTime
- java.time.chrono.HijrahDate
- java.time.chrono.JapaneseDate
- java.time.chrono.MinguoDate
- java.time.chrono.ThaiBuddhistDate
Please note that the following constraints consider null values as valid.
Constraint name | Constraint condition | Example |
---|---|---|
@Future | Value must be in the future. | @Future LocalDate validTill; |
@FutureOrPresent | Value must be in the future or now. | @FutureOrPresent LocalDateTime scheduledOn; |
@Past | Value must be in the past. | @Past LocalDate birthday; |
@PastOrPresent | Value must be in the past or now. | @PastOrPresent Date startedOn; |
The NotBlank constraint
The @NotBlank annotation can be used on strings to make sure that their values are not “blank”. The string value should satisfy the following conditions:
- Value should not be null.
- Value should have at least one non-whitespace character.
For example, values ” ab” or “\n22” are considered valid while null, ” ” or “\n\n” are not.
The annotation accepts items of the CharSequence data type.
Example usage:
@NotBlank
String name;
The NotEmpty and Size constraints
The @NotEmpty and @Size constraints can be used to enforce a minimum number of elements or a specific range of elements inside an array or a collection.
Constraint name | Constraint condition | Applicable data types | Example |
---|---|---|---|
@NotEmpty | Value must not be empty or null. When applied to string, the strings must have a length of at least 1. When applied to collections, maps and arrays, the value must have at least one item. | CharSequence, Collection, Map, Array. | @NotEmpty String name; @NotEmpty int[] myVals; |
@Size | The length/size of the given item must fall within the configured range. The range can be configured to consider the minimum and maximum number of items allowed. When applied to strings, the length of the string is evaluated. When applied to a collection, map or an array, the size is evaluated. Note that null values are considered valid. | CharSequence, Collection, Map, Array. | @Size(min = 2, max = 10) String title; |
Summary and further info
In this post, we discussed the different constraints that are made available via the JSR-303 specifications.
Depending on your bean validation implementation, you might have additional functionalities and constraints available to you. For example, the Hibernate Validator implementation offers additional constraints to validate credit card numbers, currencies and even ISBN numbers! You can check these additional constraints from hibernate validation here.
When working with bean validation, it is important to also check the documentation from your validation provider to make sure that you do not encounter any unexpected behavior.
Finally, please be careful when using bean validation annotations inside JPA models as some of them might modify the behavior of hibernate when it automatically creates your database schema.
For example, if you add the @NotNull constraint on an entity’s inner variable, hibernate will declare the column as “not null” in the SQL creation statement.
We will explore the relationship between bean validation and Hibernate in more depth in a later tutorial.
We hope you enjoyed this tutorial and that you could use it as a reference when working with Java validation.