Spring Boot Validation: Jakarta Validators and Spring-Specific Validators.
Jakarta Validation (formerly Bean Validation) provides a powerful way to validate data in Java applications, including Spring Boot projects. It includes various built-in constraints and allows for the creation of custom validators. This guide explores built-in validators with practical Java code examples and demonstrates how to define a custom validator that returns error messages using message.properties.
Pom Dependencies
pom.xml
file. These dependencies provide support for Jakarta Validation and Spring Boot's built-in validation capabilities. In this section, we will list the essential dependencies and explain their purpose to ensure seamless integration and robust data validation.<properties>
<java.version>22</java.version>
<spring.boot.version>3.4.2</spring.boot.version>
</properties>
<dependencies>
<!-- Spring Boot Starter Web (to use REST Controllers) -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Spring Boot Starter Validation (includes Jakarta Validation and Hibernate Validator) -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<!-- Spring Boot Starter Test (for testing validation logic) -->
</dependencies>
Validators in Jakarta Lib Bean Validator
Here is the complete list of available validators in Jakarta Validation (Bean Validation 3.0).
@NotNull
@NotNull(message = "{NotNull.error}")
private String username;
@NotEmpty
@NotEmpty
private String email;
@NotBlank
@NotBlank
private String fullName;
@Size(min, max)
@Size(min = 3, max = 10)
private String nickname;
@Min(value)
@Min(18)
private int age;
@Max(value)
@Max(100)
private int discountPercentage;
@Positive
@Positive
private int quantity;
@PositiveOrZero
@PositiveOrZero
private int stock;
@Negative
@Negative
private int temperature;
@NegativeOrZero
@NegativeOrZero
private int balance;
private String email;
@Pattern(regexp)
@Pattern(regexp = "\\d{10}")
private String phoneNumber;
@Past
@Past
private LocalDate birthDate;
@PastOrPresent
@PastOrPresent
private LocalDateTime lastUpdate;
@Future
@Future
private LocalDate reservationDate;
@FutureOrPresent
@FutureOrPresent
private LocalDateTime startTime;
@Digits(integer, fraction)
@Digits(integer = 5, fraction = 2)
private BigDecimal price;
@CreditCardNumber
@CreditCardNumber
private String creditCard;
@Length(min, max)
@Length(min = 5, max = 15)
private String password;
@URL
@URL
private String website;
@Range(min, max)
@Range(min = 1, max = 100)
private int score;
@Valid
@Valid
private Address address;
Additional Validators in Hibernate Validator
@ScriptAssert(lang, script, alias)
Description: Allows executing a script to validate an object. Example: Password and confirmation must match.@ScriptAssert(lang = "javascript", script = "_this.password.equals(_this.confirmPassword)")
public class User {
private String password;
private String confirmPassword;
}
@SafeHtml (Deprecated)
@EAN
@EAN
private String productCode;
@ISBN
@ISBN
private String bookCode;
@LuhnCheck
@LuhnCheck
private String creditCardNumber;
@Mod10Check and @Mod11Check
@Mod10Check
private String iban;
@Currency
@Currency
private String currencyCode;
@UUID
@UUID
private String userId;
@UniqueElements
@UniqueElements
private List<String> emails;
Spring Valid annotation
Spring provides additional options with Spring Boot Validation.
@Valid
Description: Allows validation of method parameters in a controller or service.
Example:
@RestController
public class UserController {
@PostMapping("/users")
public ResponseEntity<String> createUser(@Valid @RequestBody User user) {
return ResponseEntity.ok("User created");
}
}
Custom Validation
Defining the Annotation
import jakarta.validation.Constraint;
import jakarta.validation.Payload;
import java.lang.annotation.*;
@Documented
@Constraint(validatedBy = UppercaseValidator.class)
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Uppercase {
String message() default "{uppercase.error}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
Implementing the Validator
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
public class UppercaseValidator implements ConstraintValidator<Uppercase, String> {
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
return value != null && value.equals(value.toUpperCase());
}
}
Using the Validator
public class User {
@Uppercase
private String username;
}
Error Message Definition
In message.properties file:
uppercase.error = The field must contain only uppercase letters.
Defining Error Messages in message.properties
To customize messages in built-in validators, modify message.properties:
NotNull.error = This field cannot be null.
NotEmpty.error = This field cannot be empty.
NotBlank.error = This field cannot be blank.
Size.error = The length must be between {min} and {max} characters.
Pattern.error = Invalid format.
Email.error = Please enter a valid email address.
Min.error = The value must be at least {value}.
Max.error = The value must be at most {value}.
Positive.error = The value must be positive.
PositiveOrZero.error = The value must be zero or greater.
Negative.error = The value must be negative.
NegativeOrZero.error = The value must be zero or lower.
Digits.error = The number must have at most {integer} integer digits and {fraction} fractional digits.
Past.error = The date must be in the past.
PastOrPresent.error = The date must be in the past or today.
Future.error = The date must be in the future.
FutureOrPresent.error = The date must be in the future or today.
Length.error = The length must be between {min} and {max} characters.
CreditCardNumber.error = Invalid credit card number.
URL.error = Invalid URL.
UniqueElements.error = The list must contain unique elements.
Conclusion
Jakarta Validation provides a robust system for data validation. In this guide, we explored built-in validators, their examples, and how to create a custom validator with message properties. These validation techniques help maintain data integrity and user input validation in enterprise applications. 🚀
Reference
I am passionate about IT technologies. If you’re interested in learning more or staying updated with my latest articles, feel free to connect with me on:
Feel free to reach out through any of these platforms if you have any questions!
Comments
Post a Comment