Bean Validation Made Simple With JSR 303
Join the DZone community and get the full member experience.
Join For FreeJSR 303 (Bean Validation) is the specification of the Java API for JavaBean validation in Java EE and Java SE. Simply put it provides an easy way of ensuring that the properties of your JavaBean(s) have the right values in them. This post aims to show you how to use the Bean Validation API in your project.
To begin, imagine that you were building the next Facebook and you would need member(s) to register to use your application. In order to successfully register, prospective member(s) have to provide the following: a last name, a first name, a gender, an email address and a date of birth. In addition, the individual who is registering must be between 18 and 150 years inclusive.
Prior to JSR 303, you probably would have needed a bunch of if-else statements to achieve the above requirements. Thankfully, not any more.
We will begin by creating a JavaBean named 'Member' that would hold all the properties we are interested in.
package validationapiblog.model; import java.util.Date; import validationapiblog.enums.Gender; /** * * @author Adedayo Ominiyi */ public class Member { private String lastName = null; private String firstName = null; private Gender gender = null; private String emailAddress = null; private Date dateOfBirth = null; public Member() { } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public Gender getGender() { return gender; } public void setGender(Gender gender) { this.gender = gender; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public Date getDateOfBirth() { return dateOfBirth; } public void setDateOfBirth(Date dateOfBirth) { this.dateOfBirth = dateOfBirth; } public Integer getAge() { if (this.dateOfBirth != null) { // calculate age of member here } return null; } public String getEmailAddress() { return emailAddress; } public void setEmailAddress(String emailAddress) { this.emailAddress = emailAddress; } }The gender property is a simple enum and is shown below
package validationapiblog.enums; /** * * @author Adedayo Ominiyi */ public enum Gender { MALE, FEMALE; }
Now that we have the pieces to the puzzle. The next step is to download an implementation of JSR 303. For this post we would be using the reference implementation namely Hibernate Validator. The version as at the time this post was written is 4.2.0 Final. After downloading it you should add the following 4 jars to the classpath of your project:
- hibernate-validator-4.2.0.Final.jar
- hibernate-validator-annotation-processor-4.2.0.Final.jar
- slf4j-api-1.6.1.jar
- validation-api-1.0.0.GA.jar
Once this is done, you simply annotate the 'Member' JavaBean we created earlier to indicate which properties need be validated. You can annotate either the fields or the accessor (or getter) methods of the JavaBean. In this post I will be annotating the accessor methods.
package validationapiblog.model; import java.util.Date; import javax.validation.constraints.Max; import javax.validation.constraints.Min; import javax.validation.constraints.NotNull; import javax.validation.constraints.Past; import javax.validation.constraints.Pattern; import org.hibernate.validator.constraints.Email; import org.hibernate.validator.constraints.NotBlank; import validationapiblog.enums.Gender; /** * * @author Adedayo Ominiyi */ public class Member { private String lastName = null; private String firstName = null; private Gender gender = null; private String emailAddress = null; private Date dateOfBirth = null; public Member() { } @NotNull(message = "First name is compulsory") @NotBlank(message = "First name is compulsory") @Pattern(regexp = "[a-z-A-Z]*", message = "First name has invalid characters") public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } @NotNull(message = "Gender is compulsory") public Gender getGender() { return gender; } public void setGender(Gender gender) { this.gender = gender; } @NotNull(message = "Last name is compulsory") @NotBlank(message = "Last name is compulsory") @Pattern(regexp = "[a-z-A-Z]*", message = "Last name has invalid characters") public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } @Past(message = "Date of Birth must be the past") @NotNull public Date getDateOfBirth() { return dateOfBirth; } public void setDateOfBirth(Date dateOfBirth) { this.dateOfBirth = dateOfBirth; } @Min(value = 18, message = "Age must be greater than or equal to 18") @Max(value = 150, message = "Age must be less than or equal to 150") public Integer getAge() { if (this.dateOfBirth != null) { // calculate age of member here } return null; } @NotNull(message="Email Address is compulsory") @NotBlank(message="Email Address is compulsory") @Email(message = "Email Address is not a valid format") public String getEmailAddress() { return emailAddress; } public void setEmailAddress(String emailAddress) { this.emailAddress = emailAddress; } }
Please note that these are just some of the annotations available in JSR 303. In addition Hibernate Validator introduces a few of its own that are not in the specification. Feel free to study the annotations not in this post in your free time you might find something interesting. There is also the ability to create your own custom validator if the need arises. Now lets review the annotations used:
- @NotNull - Checks that the annotated value is not null. Unfortunately it doesn't check for empty string values
- @Pattern - Checks if the annotated string matches the regular expression given. We used it to ensure that the last name and first name properties have valid string values
- @Past - The annotated element must be a date in the past.
- @Min - The annotated element must be a number whose value must be greater or equal to the specified minimum
- @Max - The annotated element must be a number whose value must be lower or equal to the specified maximum
- @NotBlank - Checks that the annotated string is not null and the trimmed length is greater than 0. This annotation is not in JSR 303
- @Email - Checks whether the specified string is a valid email address. This annotation is also not in JSR 303
To test the validation we could use a unit test as shown below.
package validationapiblog.test; import java.util.Set; import javax.validation.ConstraintViolation; import javax.validation.Validation; import javax.validation.Validator; import javax.validation.ValidatorFactory; import validationapiblog.model.Member; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Adedayo Ominiyi */ public class ValidationAPIUnitTest { public ValidationAPIUnitTest() { } @Test public void testMemberWithNoValues() { Member member = new Member(); // validate the input ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); Validator validator = factory.getValidator(); Set<constraintviolation<member>> violations = validator.validate(member); assertEquals(violations.size(), 5); } } </constraintviolation<member>
In conclusion, you should experiment with JSR 303 and see for yourself which annotations you like. Thank you and have fun.
Original URL: Bean Validation Made Simple With JSR 303
Spring Framework
Opinions expressed by DZone contributors are their own.
Comments