简体   繁体   中英

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.

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.

You could maybe use JS validation.

JSP:

<s:checkbox id="other" name="other" />
<s:textfield id="otherDetails" name="otherDetails"></s:textfield>

<sx:submit 
            id="button_submit"
            name="button_submit"
            onclick="return checkOther();" />   

JS:

function checkOther() {
    if(document.getElementById('other').checked == true) {
        if(document.getElementyById('otherDetails').value.length == 0) {
            //you should trim the value
            alert("Insert other details");
            return false;
        }
    }

    return true;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM