Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Struts2 validation for conditional validation?

Can Struts2 be used for conditional validation? As in, if checkbox "Other" is filled in, then field "otherDetails" must not be empty?

Note that I'm looking for Struts2, not Struts1. Any example is greatly appreciated.

like image 936
Eric Wilson Avatar asked Feb 24 '10 20:02

Eric Wilson


People also ask

How does Struts 2 validation work?

When the user presses the submit button, Struts 2 will automatically execute the validate method and if any of the “if” statements listed inside the method are true, Struts 2 will call its addFieldError method. If any errors have been added, then Struts 2 will not proceed to call the execute method.

Which type of validation we must implement the Validateable interface?

1) By Custom Validation Here, we must implement the Validateable interface (or extend ActionSupport class) and provide the implementation of validate method. 2) By Input Validation (built-in validators) Struts 2 provides a lot of predefined that can be used in struts 2 application to perform validation.


1 Answers

You can probably use an expression validator. If you're validating via XML, you should have something like:

<validators>

  <validator type="expression">
    <param name="expression">(other && (otherDetails!=null && otherDetails.trim()!=""))</param>
    <message>You must provide other details.</message>
  </validator>

</validators>

See http://struts.apache.org/2.2.1/docs/validation.html for more info.

like image 60
jmibanez Avatar answered Nov 14 '22 18:11

jmibanez