XWork's validators work great when you need to apply a common validation to your Action, particularly syntatic validations that simply check values for the correct format. In a real world application, you might need to execute custom validation code that runs checks that are specific to an Action. XWork allows you to, by implementing the Validatable interface, define a custom validate() method on your action, which will be called before the Action will be executed. For example, say you were developing a To Do list application, which contains a form that allows the user to modify an existing todo entry. You need to create an Action which processes the submitted information and updates the todo information in database. To check that the fields' values were in the correct formation, you might use the following XWork validators on the following fields:
However, you want to make sure the id of the todo form actually exists before you have the business layer make update the database. While the XWork validators checked that the id field existed and contained a numeric value, you need to ensure custom validation code will be called during the validation process. The solution is to have your Action implement the Validatable interface, which defines a validate() method that you must implement. If your action has the DefaultWorkflowInterceptor in its interceptor stack, your validate() method will be called. If the validate() method, or any validators previously have generated any error messages, the chain will abort processing and return the Action.INPUT result (see DefaultWorkflowInterceptor for more information). This is what the validate() method of our todo Action, which extends ActionSupport, might look like: public void validate() { if (todoManager.getTodo(id) == null) { String error = getText("todo.err.notFound"); addActionError(error); } } The todoManager variable is a instance of the business management object that handles all todo database operations. If the id field as submitted by the form doesn't exist, we lookup the text for the error and add it as an action error. If, however, you allowed todo entries to be modified in an other area of the application, you might consider converting this code into a custom Validator to avoid code duplication. See Building a Validator for details. |