Struts 2 Custom Validation - Workflow Interceptor
We can define our own validation logic (custom validation) in struts 2 by implementing the Validateable interface in the action class.
The workflow interceptor is used to get information about the error messages defined in the action class.
The workflow interceptor checks if there is any validation errors or not. It doesn't perform any validation.
It is applied when action class implements the Validateable interface. The input is the default parameter for this interceptor that determines the result to be invoked for the action or field error.
It is found in the defaultStack so we don't need to define it explicitly.
Parameters of workflow interceptor
There is only 1 parameter defined for workflow interceptor.
The Validateable interface must be implemented to perform validation logic in the action class. It contains only one method validate() that must be overridden in the action class to define the validation logic. Signature of the validate method is:
The ValidationAware interface can accept the field level or action class level error messages. The field level messages are kept in Map and Action class level messages are kept in collection. It should be implemented by the action class to add any error message.
Methods of ValidatationAware interface
The methods of ValidationAware interface are as follows:
Note: ActionSupport class implements Validateable and ValidationAware interfaces, so we can inherit the ActionSupport class to define the validation logic and error messages.
Steps to perform custom validation
The steps are as follows:
Example to perform custom validation
In this example, we are creating 4 pages :
1) Create index.jsp for input
This jsp page creates a form using struts UI tags. It receives name, password and email id from the user.index.jsp
2) Create the action class
This action class inherits the ActionSupport class and overrides the validate method to define the validation logic.RegisterAction.java
3) Define a input result in struts.xml
This xml file defines an extra result by the name input, that will be invoked if any error message is found in the action class.struts.xml
4) Create view component
It is the simple jsp file displaying the information of the user.welcome.jsp
Defining action level error message
The action level error message works for the whole form. We can define the action level error message by addActionError() method of ValidationAware interface in validate() method. For example:
Now you need to use actionerror tag in index.jsp file to display the action level error message.index.jsp