Validating using regular expressions

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.

Getting ready

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:

  • C Requires the use of corrective lenses
  • A Must be accompanied by an adult driver
  • 6 Limited to vehicles with 6 or less axles
  • N Not permitted to drive at night

How to do it...

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;

How it works...

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

See also

The Using the Validator class recipe illustrates the use of this annotation.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.216.232.11