Java Reference
In-Depth Information
First, pull out the ContactDao interface, and add a method to search
for a contact by email address:
Download email_06/src/stripesbook/dao/ContactDao.java
package stripesbook.dao;
public interface ContactDao {
public List<Contact> read();
public Contact read(Integer id);
public void save(Contact contact);
public void delete(Integer id);
public Contact findByEmail(String email);
}
Next, assume that the code for this method is in the MockContactDao
class. Again, don't bother with the implementation details.
Now, since we need to query the DAO to perform the unique email
validation, implement a validation method in ContactFormActionBean :
Download email_06/src/stripesbook/action/ContactFormActionBean.java
@ValidationMethod(on="save")
public void validateEmailUnique(ValidationErrors errors) {
String email = getContact().getEmail();
Contact other = getContactDao().findByEmail(email);
if (other != null && !other.equals(getContact())) {
errors.add("contact.email", new SimpleError(
"{1} is already used by {2}.", other));
}
}
We'll want to use on="save" so that the validation method will be exe-
cuted only for the save ( ) event handler of ContactFormActionBean .
This method is executed only if there are no previous errors. This is
handy because there's no point in checking whether the email is already
in use if the email input is omitted or if the format is invalid.
Using the contact DAO to find the contact that has the entered email
address, the code flags a validation error if a contact was found and is
different from the one being updated in the form. Using {1} and {2} , the
email address and the name of the other contact are included in the
error message.
Now, if the user enters an email that is already in use by another con-
tact, we'll get the result shown in Figure 4.8 , on the next page.
 
Search WWH ::




Custom Search