Master JSR‑303 Bean Validation: Rules, Annotations, and Practical Code Samples
This article introduces JSR‑303 Bean Validation, lists required JARs, explains core constraint annotations for null, boolean, size, date, and numeric checks, and provides complete Java code examples demonstrating how to apply and test these validations in a Spring MVC environment.
1. Introduction to JSR-303
JSR-303 is a sub‑specification of Java EE 6 called Bean Validation; the reference implementation is Hibernate Validator, which is unrelated to Hibernate ORM. It validates field values of Java beans and is fully supported by Spring MVC 3.x for form data.
2. Required JARs
validation-api-1.0.0.GA.jar provides the API, hibernate-validator-4.2.0.Final.jar implements it, and logging libraries such as log4j, slf4j, and slf4j-log4j are also needed.
3. Basic Validation Constraints
Null checks
@Null – the element must be null
@NotNull – the element must not be null (empty strings are allowed)
@NotBlank – the string must be non‑null and contain at least one non‑whitespace character
@NotEmpty – the element must not be null or empty
Boolean checks
@AssertTrue – the Boolean must be true
@AssertFalse – the Boolean must be false
Size checks
@Size(min=…, max=…) – validates length of arrays, collections, maps or strings
@Length(min=…, max=…) – validates string length (inclusive)
Date checks
@Past – the date must be in the past
@Future – the date must be in the future
@Pattern – the string must match a regular expression
Numeric checks
@Min, @Max – numeric or string value must be greater/less than or equal to the given bound
@DecimalMin, @DecimalMax – same as Min/Max but with BigDecimal precision
@Digits – validates number of integer and fractional digits
@Range – validates that a value lies within a given range
@CreditCardNumber – validates credit‑card numbers
@Email – validates e‑mail address (null values are ignored)
@URL – validates URL components
@ScriptAssert – custom script validation
Nested validation
@Valid – triggers recursive validation of associated objects or collections
4. Example
public class Order {
@NotNull
@Size(min = 10, max = 10)
private String orderId;
@NotEmpty
private String customer;
@Email
private String email;
@NotEmpty
private String address;
@NotNull
@Status // must be one of 'created','paid','shipped','closed'
private String status;
@Valid
private Product product;
}Another example with custom messages and numeric constraints:
@NotNull(message = "adultTax cannot be null")
private Integer adultTax;
@NotNull(message = "adultTaxType cannot be null")
@Min(value = 0, message = "adultTaxType minimum is 0")
@Max(value = 1, message = "adultTaxType maximum is 1")
private Integer adultTaxType;
@NotNull(message = "reason cannot be empty")
@Pattern(regexp = "[1-7]{1}", message = "reason must be a digit 1‑7")
private String reason;5. Full Validation Class
public class ValidateTestClass {
@NotNull(message = "reason cannot be null")
@Pattern(regexp = "[1-7]{1}", message = "reason must be a digit 1‑7")
private String reason;
public void validateParams() {
Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
Set<ConstraintViolation<ValidateTestClass>> violations = validator.validate(this);
if (!violations.isEmpty()) {
String errMessage = violations.iterator().next().getMessage();
throw new ValidationException(errMessage);
}
}
}A JUnit test can instantiate the class, set an invalid value, and call validateParams() to see the exception.
Note: Validation annotations must match the data type they are applied to; for example, @Pattern works only on String fields. Applying it to an Integer results in
javax.validation.UnexpectedTypeException: HV000030: No validator could be found for type: java.lang.Integer.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Java Backend Technology
Focus on Java-related technologies: SSM, Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading. Occasionally cover DevOps tools like Jenkins, Nexus, Docker, and ELK. Also share technical insights from time to time, committed to Java full-stack development!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
