Java Reference
In-Depth Information
applies a regular expression match against the field value and returns the Boolean
result of the match. Imagine the following form input fields corresponding to our
FieldType instances:
<input type="password" name="password" value=""/>
<input type="tel" name="phone" value=""/>
<input type="email" name="email" value=""/>
<input type="text" name="ssn" value=""/>
The value of the input field's name attribute will be used to identify the
FieldType ; you used this same name when you instantiated each FieldType
enum constant. When a form is submitted, you have access to each input field's name
and the value that was entered into the field. You need to be able to map the field's
name to a FieldType and call the validate() method with the input value. The
class variable, nameToFieldTypeMap , is declared and initialized for this purpose.
For each FieldType enum constant, nameToFieldTypeMap stores an entry
with the field name as the key, and the FieldType as the value. The look-
up(String) class method uses this map to look up the FieldType from the field
name. The code to validate an email input field with an input value of
john@doe.com is quite concise:
// <input type="email" name="email" value="john@doe.com"/>
String fieldName = "email";
String fieldValue = "john@doe.com";
boolean valid
= FieldType.lookup(fieldName).validate(fieldValue);
The main() method shows an example validation for each of the FieldTypes .
The printValid() method prints the field name, field value, and the field's valida-
tion result.
This recipe has demonstrated that there is a lot more potential in the enum type
than just the ability to define a set of named constants. Enum types have all the power
of a normal class, plus additional features that allow you to create well-encapsulated
and intelligent constants.
Search WWH ::




Custom Search