Struts 2 validate field if not empty
There are two fields email and phone number (integer) in a form.开发者_运维百科 The form is validated using the struts validation framework (ActionClass-validation.xml). These two fields are optional, so the user can leave them blank. But if they are not blank the fields need to be validated. Please help me find out how to write validators in xml to do this.
You can also use annotations. In my opinion it's more clear to understand and easy to write and debug. This is an example:
@EmailValidator(type = ValidatorType.SIMPLE, message = "", key = "validation.email")
public String getEmail() {
return email;
}
For the number, you can use a regex validator:
@RegexFieldValidator(key = "validation.number", message = "", type = ValidatorType.SIMPLE, expression = NUMBER_PATTERN_STRING)
public String getNumber() {
return number;
}
In your jsp you can reference the errors using field (or action) error tags:
<s:fielderror fieldName="email" cssClass="myerrorclass"/>
<s:textfield name="email" cssClass="myclass" cssErrorClass="myothererrorclass"/>
I hope the code is quite self-explanatory. Happy coding! ;)
Try this
<field name="email">
<field-validator type="email">
<message>Invalid Email (empty email accepted)</message>
</field-validator>
</field>
<field name="contact">
<field-validator type="regex">
<param name="expression"><![CDATA[([1234567890]+)]]></param>
<message>Invalid Contact Number (empty number accepted)</message>
</field-validator>
</field>
Here is a complete example.
精彩评论