Jakarta Bean Validation Annotations
About
Here is a table for all core annotations in the Jakarta Bean Validation API (jakarta.validation.constraints)
Note
All annotations belong to the package:
jakarta.validation.constraints.*Use
@Validon fields or method parameters to trigger validation recursively for complex/nested objects.These annotations are declarative and interpreted at runtime by a
Validatorimplementation (like Hibernate Validator).
Table
@NotNull
All types
Ensures that the value is not null. Commonly used for required fields. Does not check for emptiness (e.g., "" is valid).
@Null
All types
Ensures the value is null. Rarely used alone, but can be useful with validation groups (e.g., id must be null during creation).
@NotEmpty
String, Collection, Map, Array
Ensures the value is not null and not empty. For strings, "" fails. For collections/maps, size > 0 is required.
@NotBlank
String only
Stronger than @NotEmpty. Ensures string is not null, not "", and not only whitespace.
@Size(min=, max=)
String, Collection, Map, Array
Ensures that the length or size falls within the specified bounds.
@Min(value)
Numeric types (int, long, etc.)
Ensures that the value is greater than or equal to the specified minimum.
@Max(value)
Numeric types
Ensures the value is less than or equal to the specified maximum.
@DecimalMin(value, inclusive=true)
Numeric types, String, BigDecimal
Ensures the value is ≥ the specified decimal value. inclusive=false allows exclusive min.
@DecimalMax(value, inclusive=true)
Same as above
Ensures the value is ≤ the specified decimal value.
@Positive
Numeric types
Ensures the value is strictly greater than 0.
@PositiveOrZero
Numeric types
Ensures the value is 0 or greater.
@Negative
Numeric types
Ensures the value is strictly less than 0.
@NegativeOrZero
Numeric types
Ensures the value is less than or equal to 0.
@Digits(integer=, fraction=)
Numeric types
Ensures the number has up to integer digits before the decimal and fraction digits after.
@Past
Date, Calendar, LocalDate, etc.
Ensures the date is before the current time.
@PastOrPresent
Same as above
Ensures the date is either in the past or now.
@Future
Same as above
Ensures the date is strictly in the future.
@FutureOrPresent
Same as above
Ensures the date is in the future or now.
@Pattern(regexp="...")
String only
Validates the string against the given regular expression. Commonly used for phone numbers, usernames, etc.
@Email
String only
Ensures that the string is a valid email address. Also accepts a regexp for stricter formats.
@AssertTrue
boolean, Boolean
Validates that the value is true. Commonly used for checkboxes or policy acceptance.
@AssertFalse
boolean, Boolean
Validates that the value is false.
@Valid
Object, Collection of objects
Triggers nested validation. This is required if the validated bean has fields or properties that are other beans with their own validation annotations.
@GroupSequence
On interfaces
Used to define the order in which validation groups are evaluated. If a group fails, later ones are skipped.
@ConvertGroup(from=, to=)
On @Valid annotated fields
Allows converting one validation group to another for nested beans. Used when different rules apply depending on parent context.
@ReportAsSingleViolation
On custom composed annotations
When used in a composed constraint, makes sure the composed annotation reports only a single violation message, not one per sub-constraint.
@Constraint(validatedBy=...)
Custom annotation
This is used to mark a custom constraint annotation and specify the associated validator implementation. Mandatory for creating your own validation annotations.
What is @Valid and @Validated Annotation ?
@Valid
@Valid@Validis part of Jakarta Bean Validation (jakarta.validation.Valid).It tells Spring or the Validator to perform validation on the object it is placed on.
It can be used on:
Method parameters (especially in controllers)
Fields (for nested validation)
Inside service or other layers when using the Validator API
Use Cases and Working
1. Controller-level validation (with @RequestBody):
@PostMapping("/users")
public ResponseEntity<Void> createUser(@RequestBody @Valid UserDto userDto) {
// If userDto is invalid, Spring will return 400 Bad Request with error details.
}Explanation:
When Spring sees
@Validon@RequestBody, it checks theUserDtoclass for validation annotations (@NotNull,@Size, etc.).If validation fails, Spring automatically returns a
400 Bad Request.You don’t need to write any manual validation logic.
2. Nested object validation:
public class Order {
@Valid
private Customer customer;
}Explanation:
When validating an
Order, Spring/Validator will recursively validate theCustomerobject if it's annotated with@Valid.
3. Manual validation (in service or elsewhere):
Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
Set<ConstraintViolation<UserDto>> violations = validator.validate(userDto);Explanation:
We explicitly call the validator and check the result.
Useful when we're outside the controller (e.g., in services, CLI apps).
@Validated
@Validated@Validatedis provided by Spring (org.springframework.validation.annotation.Validated).It enhances
@Validby adding:Validation Groups support
Method-level validation (when used on Spring-managed beans)
Use Cases and Working
1. Validation groups (selective validation):
@PostMapping("/users")
public ResponseEntity<Void> createUser(@RequestBody @Validated(Create.class) UserDto userDto) {
// Only constraints marked with Create.class will be validated
}Explanation:
We can define multiple validation scenarios using interfaces (
Create,Update, etc.).Use them to apply different rules depending on the operation (create, update).
2. Service-layer method validation:
@Validated
@Service
public class UserService {
public void updateUser(@Valid @NotNull UserDto userDto) {
// Spring AOP intercepts this and performs validation on method parameters.
}
}Explanation:
1. @Validated on the UserService class:
@Validated on the UserService class:@Validatedis a Spring annotation that triggers method-level validation.When applied at the class level, Spring will automatically validate method parameters marked with validation annotations (like
@Valid,@NotNull) for every method in the class.It works by using Spring AOP (Aspect-Oriented Programming). A proxy is created around the
UserServiceclass, and this proxy intercepts method calls to validate the parameters of the method before execution.Key point: This will only work if
UserServiceis a Spring-managed bean (i.e., it is created by Spring’s IoC container, which is the case because it's annotated with@Service).
2. @Service on the UserService class:
@Service on the UserService class:The
@Serviceannotation marks this class as a Spring service component.Spring will manage this class, and it will be available for dependency injection in other parts of your application.
This means Spring will automatically create an instance of
UserServicewhen needed and apply any AOP (like validation) to its methods.
3. @Valid on the userDto parameter:
@Valid on the userDto parameter:The
@Validannotation is a Jakarta Bean Validation annotation (jakarta.validation.Valid).It triggers the validation of the
userDtoobject and all its nested properties.Spring will check whether the
userDtoobject and its fields conform to any constraints defined in theUserDtoclass (such as@NotNull,@Size, etc.).If the
userDtois invalid (i.e., one of its constraints is violated), Spring will throw an exception or return a 400 Bad Request if used in a controller.
4. @NotNull on the userDto parameter:
@NotNull on the userDto parameter:The
@NotNullannotation is a constraint that indicates theuserDtocannot benull.This works in conjunction with
@Validto ensure that not only theuserDtoobject is validated, but also that theuserDtoitself is notnull.If the
userDtoisnull, a validation violation occurs.
Last updated