Regular expressions provide a powerful technique for validating fields. Phone numbers and Zip codes can be easily verified using regular expressions. The @Pattern annotation allows us to use a regular expression to verify the correct usage of these types of fields.
We will use the LicenseBean
and LicenseBeanFacade
classes from the ValidationApplication
as discussed in the Validating persistent fields and properties recipe.
In order to illustrate the use of regular expressions we need to define allowable values for the restrictions field. This field may hold a combination of values reflecting driving constraints such as:
The @Pattern annotation uses a regexp
argument to define a regular expression. The regular expression is applied to the field declaration that follows it. Regular expressions follow the convention as defined in java.util.regex.Pattern
.
Let's start by using a simple regular expression to test for patterns which meet these restrictions. The "??" regular expression qualifiers specify that the preceding character will appear once or not all.
@Pattern(regexp="C??A??6??N??") private String restrictions;
More sophisticated regular expressions can be developed. For example, a zipCode
field might be defined as follows:
@Pattern(regexp="\d{5}(-\d{4})?") private String zipCode;
Regular expressions provide a powerful, if not sometimes cryptic, technique for validating more complex string patterns. It is not possible to adequately cover regular expression in this recipe. There are a number of books that are devoted entirely to this topic.
The Validator
class is used in conjunction with this annotation to detect and handle violations. This technique is illustrated in the Using the Validator Class recipe
18.216.232.11