Java Reference
In-Depth Information
Matcher matcher = pattern.matcher(input);
if (matcher.matches()) {
result = new PhoneNumber(
matcher.group(1), matcher.group(2), matcher.group(3));
}
else {
errors.add( new SimpleError("{1} is not a valid {0}"));
}
return result;
}
public void setLocale(Locale locale) {
}
}
The regular expression pattern is from the mask= attribute of the phone
number validation in Section 4.2 , Using Regular Expression Masks, on
page 82 . Grouping with parentheses around the digits for the area code,
prefix, and suffix (see Figure 5.4 , on the following page) makes it easy to
extract those parts of the phone number and construct a PhoneNumber
object. If the input does not match the regular expression, a validation
error is added to the list of errors.
We're using SimpleError here, which is fine for our purposes at this point.
However, we can create validation errors without hard-coding the mes-
sage in the code but rather by having the message in a resource bundle.
We'll see how it's done in Chapter 6 , Customizing Stripes Messages, on
page 121 .
Now that we have a type converter for phone numbers, how do we use
it? First, remove the mask= attribute from @Validate since the phone
number validation has been moved to the type converter. Next, use the
converter= attribute.
@ValidateNestedProperties({
@Validate(field="phoneNumber",
converter=PhoneNumberTypeConverter. class )
// (removed mask="...")
// (other validations...)
})
@Override
public void setContact(Contact contact) {
super .setContact(contact);
}
We can also tell Stripes to use PhoneNumberTypeConverter by default for
every PhoneNumber property. All we have to do is configure a package
for extensions (see the sidebar on page 115 ) and put the PhoneNum-
berTypeConverter class in that package. Now we can use PhoneNumber
 
 
Search WWH ::




Custom Search