Struts2 Validation with Example

Struts Validation is plugin is a mandatory and important for any web application, Validating is an important part of any web framework because it is one of the most painfully repetitive things to do.  In Struts 2, validation plugin is created with use of an < ActionClassName>-validation.xml file.  So, if we have an AddEmployee Action then we would create an AddEmployee-validation.xml file, Please find below one for AddEmployee:

<!DOCTYPE validators PUBLIC "-//OpenSymphony Group//XWork Validator 1.0.2//EN"
"http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd">

<validators>
<field name="employeeId">
<field-validator type="requiredstring">
<message>Employee Name is required.</message>
</field-validator>
</field>
</validators>
 

It is *required to have both getters and setters for the field you are validating for.  As class AddEmployee will require both of the following method signatures for validation to work properly: “public String getEmployeeId()” and “public void setEmployeeId(String EmployeeId)”.  You can get more information about the other types of validators at official site of struts – Struts 2 documentation.
You can also control error handling from your Action class.  For example, let’s say that the user picks a username which is already registered.  We wouldn’t be able to determine this with validation alone, but would need to check the database in our Action class.  So when we determine that we can call “addActionError(String message)” from our class.  Then when we want to print any errors out on our page, we simply use the tag into our error page where we sould like to show error message: <s:actionerror />