Understanding JSR-303 Annotations
The JSR 303 bean validation annotations are defined as part of the javax.validation package. Some important Validation Annotations are defined below:
1. @NotNull: Ensures the annotated element is not null.
Example:
public class Student {
@NotNull(message = "Student name cannot be null")
private String name;
}
2. @NotEmpty: Checks if a String, Collection, Map, or array is not empty.
Example:
public class Student {
@NotEmpty(message = "List of marks cannot be empty")
private List<String> marks;
}
It is also applied to strings, collections, and arrays.
3. @Size Checks if the size is between the specified boundaries.
Example:
public class Student {
@Size(min = 18, message = "age cannot be less than ")
private String age;
}
4. @Min and @Max: Limits the value of a numerical property, specifying the minimum or maximum allowed value.
Example:
public class Student {
@Min(value = 1, message = "Student should have enrolled in at least one subject")
@Max(value = 4, message = "Student cannot be enrolled more than four subjects")
private double subject;
}
5. @Pattern: Checks if a String matches the given regular expression.
Example:
public class Student {
@Pattern(regexp = "\\d{3}-\\d{3}-\\d{4}", message = "Kindly Provide a Valid phone number")
private String phoneNumber;
}
6. @Email: Checks if a String is a valid email address.
Example:
public class Student {
@NotNull
@Email(message = "Please provide a valid email address")
private String email;
}
7. @URL: Checks if a String is a valid URL.
Example:
public class Student {
@URL(message = "Please enter a valid Website")
private String website;
}
8. @Past: Checks if a date/time is in the past.
Example:
public class Student {
@Past(message ="Please enter a valid Date")
private LocalDate dateOfBirth;
}
9. @Future: Checks if a date/time is in the future.
Example:
public class Admin {
@Future(message = "Due date must be in the future")
private Date admissionDueDate;
}
10. @DecimalMin and @DecimalMax: Checks decimal number ranges.
Example:
public class Admin {
@DecimalMin("100000.50")
@DecimalMax("200000.00")
private BigDecimal fees;
}
11. @Digits: Checks the number of digits of an integer or decimal number.
Example:
public class Student {
@Digits(integer = 5, fraction = 2)
private double percentage;
}
12. @AssertTrue/False: Checks if a boolean expression is true/false.
Example:
Java
public class Student { private int age; private boolean passedExam; @AssertTrue public boolean isEligibleForScholarship() { return age < 21 && passedExam; } |
Spring Bean Validation – JSR-303 Annotations
In this article, we’ll explore practical examples of how to apply JSR-303 annotations to your domain objects from basic annotations to advanced. So basically annotations provide a declarative way to configure Spring beans, manage dependencies, and define behaviors, reducing the need for boilerplate code and making your code more concise and expressive.
Contact Us