@RequiredStringValidator and @EmailValidator in Struts 2
June 15, 2014
@RequiredStringValidator and @EmailValidator are the struts 2 validation annotations. @RequiredStringValidator checks if string field is not empty. @EmailValidator checks if a filed contains valid email or not. These validation annotation can be used in action class. After using these validations, the form fields are gets validated.
Attributes of @RequiredStringValidator
Find the attributes of @RequiredStringValidator annotation.message : This attribute is required. This displays the error message.
key : This is I18 key which is obtained from property file.
messageParams : This is a additional param which is used to customize the message.
fieldname : This denotes the field name.
shortCircuit : Enables this validator to be used as short circuit.
type : The value of type can be like ValidatorType.FIELD.
trim : Default value is true. If enables it trims the string before length check.
@RequiredStringValidator(message = "message", key = "i18n.key.value", shortCircuit = true, trim = true)
Attributes of @EmailValidator
Find the attributes of @RequiredStringValidator annotation.message : This attribute is required. This displays the error message.
key : This is I18 key which is obtained from property file.
messageParams : This is a additional param which is used to customize the message.
fieldname : This denotes the field name.
shortCircuit : Enables this validator to be used as short circuit.
type : The value of type can be like ValidatorType.FIELD.
@EmailValidator(message = "message", key = "i18n.key.value", shortCircuit = true)
@RequiredStringValidator and @EmailValidator Example in Action Class
Find the code snippet to use @RequiredStringValidator and @EmailValidator annotation in Action class. The code in JSP will not be changed regarding error message.<s:form action="result" validate="true"> <s:textfield name="name" label="Name"/> <s:textfield name="email" label="Email"/> </s:form>
@Action(value="result", results={@Result(name="success",location="result.jsp")}) public class ResultAction extends ActionSupport{ private String name; public String execute() { return SUCCESS; } @RequiredStringValidator(message = "Enter your Name.") public String getName() { return name; } public void setName(String name) { this.name = name; } @RequiredStringValidator(message = "Enter your Email.") @EmailValidator(message = "Enter a valid e-mail address." ) public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } }