How to Validate Input in Struts 2 With Annotations and XML
Validate Struts 2 form input with a validate method, XML validation files or annotations, show field errors and see how input routes failures.

A form posts text and your action wants types and rules. Struts 2 does both before your execute runs, and when something is wrong it returns the user to the form with messages. This post shows the three ways to declare rules and what happens on a failure. The setup is in the Struts 2 tutorial, and the missing input result is a common companion error: no result defined.
The flow
In the default interceptor stack the order is: params copies values onto the action, conversionError collects type conversion problems, validation runs validators, and workflow checks for errors. If there are field errors or action errors, workflow returns input and stops. Your execute runs only for a clean submission.
Style 1: the validate method
public class RegisterAction extends ActionSupport {
private String email;
private int age;
@Override
public void validate() {
if (email == null || !email.contains("@")) {
addFieldError("email", "Enter a valid email address");
}
if (age < 18) {
addFieldError("age", "You must be 18 or older");
}
}
@Override
public String execute() {
return SUCCESS;
}
// getters and setters
}This is plain Java, easy to debug and to unit test. Put the logic you cannot express declaratively here. There is also validateExecute() and validateMethodName() for per-method validation.
Style 2: XML validators
Create RegisterAction-validation.xml in the same package as the class, on the classpath:
<!DOCTYPE validators PUBLIC "-//Apache Struts//XWork Validator 1.0.3//EN"
"https://struts.apache.org/dtds/xwork-validator-1.0.3.dtd">
<validators>
<field name="email">
<field-validator type="requiredstring">
<message>Email is required</message>
</field-validator>
<field-validator type="email">
<message>Enter a valid email address</message>
</field-validator>
</field>
<field name="age">
<field-validator type="int">
<param name="min">18</param>
<message>You must be 18 or older</message>
</field-validator>
</field>
</validators>This keeps rules out of the class and is the traditional style. The file name must match the action class name; for an action alias, use ActionClass-alias-validation.xml.
Style 3: annotations
@Validations(
requiredStrings = { @RequiredStringValidator(fieldName = "email", message = "Email is required") },
emails = { @EmailValidator(fieldName = "email", message = "Enter a valid email address") })
public String execute() {
return SUCCESS;
}or on setters, @RequiredStringValidator(message = "..."). The annotation approach keeps the rule near the property. The three styles can be mixed, and all contribute field errors.
Show the errors
<s:form action="register">
<s:textfield name="email" label="Email" /> <!-- shows its own error above the field -->
<s:textfield name="age" label="Age" />
<s:submit />
</s:form>The default xhtml theme prints field errors next to each input. For a summary use <s:fielderror />. Messages can come from a resource bundle (RegisterAction.properties) with getText() for internationalization.
Conversion errors
Text in a numeric field produces a conversion error before validation:
Invalid field value for field "age".Override the message with a key in the properties file: invalid.fieldvalue.age=Age must be a number.
Client-side validation
Setting validate="true" on <s:form> generates JavaScript from the XML validators. Treat that as a convenience. The server check always runs.
Where validation messages come from
Messages are looked up in a resource bundle named after the action class, such as LoginAction.properties, with the key you give in the validator. A field error with a key that does not exist shows the key text itself, which is the cue to check the file name and its location on the classpath. Keep one bundle for common messages, and refer to it from the action bundles, so "required" is written once and translated once. Parameters in messages, like {0}, are filled from the validator's parameters, and you can show the minimum or maximum without hard-coding the number in the text.
Nested objects and lists
Forms often bind to a model object, user.email and user.age, and validation must reach it. Use the visitor field validator in XML, which delegates to the validation file of the nested class, so the rules live next to the model and apply wherever it is used. Lists of objects are validated item by item with the same mechanism, and the error key includes the index, such as items[2].quantity, which the form tags map back to the right row.
Conversion errors are not validation errors
Before validation runs, the parameters interceptor converts strings to the types of your fields. If a user types abc into an int field, the conversion fails, the field is left unset and Struts adds a conversion error with the key invalid.fieldvalue.age. If you only wrote a range validator, the user sees a generic message about an invalid value. Override the key in your bundle with text that tells them what to enter, and test the case, since it is the one that reaches every real form.
A common error to expect
If validation fails and the action has no input result mapped, Struts responds with an exception like No result defined for action ... and result input. Add <result name="input">/login.jsp</result> to the mapping, or the defaults with a global result. The error looks like a validation bug, and it is a missing line of configuration.
Testing validation
Test the action in isolation: set the fields, call validate(), and assert the field errors with getFieldErrors(). For XML or annotation validators, the Struts JUnit plugin runs the interceptor stack and lets you execute the action as the framework would. One test per rule keeps failures specific and documents the rules in a form that cannot drift from the code.
Choosing a style
Use the validate() method for rules that need code, such as comparing two fields or checking a value against a database, XML validators for the plain rules that repeat across forms such as required, length and range, and annotations when you want the rules beside the field they apply to. Mixing all three in one action makes it hard to see where a message came from. Pick one for ordinary rules and reserve the method for the exceptions, and write the choice in the project's documentation so a new action follows it.
Server rules are the real rules
Client-side validation is a convenience. It saves a round trip and nothing more, because anyone can post to the action directly and skip the script. Whatever the browser checks, the server checks again, with the same rules. Struts can generate JavaScript from the validation configuration so that the two never drift, and you can turn it on per form with validate="true" on the form tag, and keep in mind that the generated script is for the user's comfort and not a security measure.
Security of input
Validation checks shape. It does not make input safe for every use. A name that passes a length rule can still contain markup, so escape on output, which the Struts tags do by default, and use parameterized queries when the value reaches a database. Never build an OGNL expression or a file path from an input value. The same input needs different treatment where it is used, and validation is only the first gate.
Where this does not apply
Validation does not protect against malicious parameter names or values reaching the action: that is the job of the parameters interceptor's allow-list, discussed in hardening Struts 2. The Struts validation documentation lists all the built-in validators, and the interceptors documentation explains the stack that runs them.


