The Struts validation framework provides the email validator to validate if value of a String field is a valid e-mail address. We can use this validator in two forms:
NOTES: This validator does not work if the field is empty, i.e. it does not treat the empty value as invalid e-mail. So it’s recommended to use this validator in conjunction with the required string validator.
<field name="fieldName"> <field-validator type="email"> <message>validation error message</message> </field-validator> </field>
<validator type="email"> <param name="fieldName">myEmailFieldName</param> <message>validation error message</message> </validator>
Parameter name | Description |
fieldName | Name of the field to validate. Required if using plain validator syntax. |
<field name="myEmail"> <field-validator type="email"> <message>Please enter a valid e-mail address.</message> </field-validator> </field>
<validator type="email"> <param name="fieldName">myEmail</param> <message>Please enter a valid e-mail address.</message> </validator>
Usage:Annotate setter method of the String field or action method (in case of using plain-validator) by:
@EmailValidator(param1 = "param 1 value", param2 = "param 2 value", ...)
Parameter name | Required | Default value | Description |
message | Yes | validation error message. | |
key | No | i18n key for validation error message. | |
messageParams | No | Additional parameters to customize the message. | |
fieldName | No | Specifies field name in case this validator type is plain-validator. | |
shortCircuit | No | false | Whether this validator is short circuit. |
type | No | ValidatorType.FIELD | type of the validator: field-validator (FIELD) or plain-validator (SIMPLE). |
@EmailValidator(message = "Please enter a valid email address") public void setMyEmail(String myEmail) { this.myEmail = myEmail; }
@EmailValidator(message = "Default message", key = "form.validation.email") public void setMyEmail(String myEmail) { this.myEmail = myEmail; }
@EmailValidator(type = ValidatorType.SIMPLE, message = "Please enter a valid email address 4", fieldName = "myEmail") public String execute() { return SUCCESS; }
Related Struts Form Validation Tutorials: