A Wicket form validator for a list of email addresses

I needed to validate a list of email addresses entered into a Wicket text area (a cc: list of email addresses). To do this, I created a simple form validator which breaks up the list from the text area into individual email addresses and then uses the EmailAddressValidator to validate them individually. It illustrates a few Wicket techniques: (a) how to validate a field containing several values which need to be validated individually and (b) how to use a Validator against a string instead of a form component. Anyway, here’s the code in case its of use to anyone.

class CCValidator extends AbstractFormValidator implements Serializable {
	private static final long serialVersionUID = 1L;
	private final TextArea<String> cc;
 
	public CCValidator(TextArea<String> cc) {
		this.cc = cc;
	}
 
	public FormComponent<?>[] getDependentFormComponents() {
		return new FormComponent[] { cc };
	}
 
	public void validate(Form<?> form) {
		String cc_entered = cc.getConvertedInput();
		String[] ccList = cc_entered.split("\r\n");
		for (String email : ccList) {
			if (!isValidEmailAddress(email)) {
				Map<String, Object> map = super.variablesMap();
				map.put("email_address", email);
				error(cc, "invalid_cc", map);
			}
		}
	}
 
	private boolean isValidEmailAddress(final String emailAddress) {
		Validatable<String> v = new Validatable<String>(emailAddress);
		EmailAddressValidator.getInstance().validate(v);
		return v.isValid();
	}
}

To use it, add it to the form as follows:

form.add(new CCValidator(cc));
// where cc is the TextArea where the cc list should be entered

Tags:

One Response to “A Wicket form validator for a list of email addresses”

  1. Leo Says:

    Great tip! Thanks!

    We are right now in the process of migrating from JSP to Wicket. Fun days!

Leave a Reply


WordPress Appliance - Powered by TurnKey Linux