I am running into a wall on how to create custom error messages in struts 2.
I iterate through a list of email addresses and validate using a custom validator. That validator will return true if any email addresses within the list are invalid.
Here is my custom validator:
public class EmailListValidator extends FieldValidatorSupport {
@Override
public void validate(Object obj) throws ValidationException {
String fieldName = getFieldName();
String fieldValue = (String) getFieldValue(fieldName, obj);
if (fieldValue == null) return;
fieldValue = fieldValue.trim();
//
if (errorCheck(fieldValue).length() > 1) {
addFieldError(fieldName, obj);
}
}
private String errorCheck(String permList) {
if (permList.equals("")) {
return "";
}
String emailList = permList.toLowerCase();
String []emails = emailList.split(";");
emailList = "";
for (int i=0; i<emails.length; i++) {
if (emails[i].matches(EMAIL_PATTERN_STRING)) {
//Do Nothing (Email is valid - or at least appears as such)
} else {
emailList += emails[i] + "; ";
}
}
return emailList;
}
}
As stated, in this case there either is an error or there isn't; if there is an error, it displays a very general error message.
<field name="reqEmail">
<field-validator type="emaillist">
<message key="validation.reqEmail.valid" />
</field-validator>
</field>
How do I make it so the error message will state which exact email addresses were invalid?
How do I do so while still being able to refer to the message key, so the application can remain multilingual?
Create field (e.g. invalidEmails
) with getter and setter in your EmailListValidator
and assign invalid emails to it. In validation xml file you can access this property by using ${...}
notation.
<field name="reqEmail">
<field-validator type="emaillist">
<message>${getText("validation.reqEmail.valid")}: ${invalidEmails}</message>
</field-validator>
</field>