Struts - Bypassing form Validation


Web tier: servlets, JSP, Web frameworks: Struts - Bypassing form Validation

  1. Struts - Bypassing form Validation (5 messages)

    I have a constructed a profile page. It has both ADD and CANCEL button. I have done validations of the form elements in the validate() method of the form bean. It works fine with the ADD button.
    But I dont want the validate() method to be called on clicking the CANCEL button.
    In this scenario, what do I do to bypass the form bean validate() method on clicking the CANCEL button?

    Threaded Messages (5)

  2. Hi Anandha,

    I don't think that this is possible (if someone knows how, please let me know). I had a similar problem:I had a couple of buttons submitting form data on activation, whereas some should validate via ActionForm and some shouldn't. Finally, I validated the form input in the associated action. I recommend to use a LookupDispatchAction for this to separate each button-click to its own method.

    You just have to add an ActionErrors object to the request in case of errors in your input. After that, forward to the input page. The error will be displayed as usual, i.e.:

    request.setAttribute(Globals.ERROR_KEY, errors);
    return mapping.findForward("back_to_where_i_came_from");

  3. Look, another Struts hack![ Go to top ]

    Ya its possible, Download Appfuse to see the best example I have ever seen in their BaseForm. It is very similiar to what Kristian mentioned. Its a hack but you're using Struts so that is OK -;)
  4. If you want both buttons to submit to the same action mapping, then you will need to verify which button was clicked in your validate() method, so the method itself cannot be bypassed. Or, you can define Cancel button in a separate form and submit it to a different action mapping (possibly using the same form bean). In the latter case just set Action.Validate attribute of the action mapping to "false".
  5. In your JSP....
    - add hidden field, either via INPUT tag (you won't need a corresponding field on your Form), or if preferred, via html:hidden in which case you will need to add a Form field). I prefer via INPUT tag so it's not "bound" to the form and you don't have to worry about the state of the field in the Form.

    - add a Javascript function that
      1. sets the hidden field to some value like "cancel"
      2. submits your form

    - attach the function to the onclick of your cancel button

    In your ActionForm....
    - in your validate() method, check the request parameter represented by the hidden field and perform the validation only if value is not "cancel"
  6. Hummmm, Change your struts-config.xml validation=false and execute method manually on add and on cancal bypass it. cheat to struts but hey!!!