【问题标题】:struts 2 checkboxlist validation questionstruts 2 checkboxlist验证问题
【发布时间】:2010-02-24 15:10:11
【问题描述】:

我有如下的 struts 2 复选框列表:

<s:checkboxlist list="listOfOptions" name="someName" />

我想添加验证以确保至少有一个复选框已被选中。有什么想法吗?

谢谢

【问题讨论】:

    标签: validation struts2


    【解决方案1】:

    我使用 JS 来做到这一点。

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

    还有 JS:

    function validateNotEmptyCheckbox() {
        var checkboxes = document.getElementsByTagName('input');
        for (i = 0; i < arguments.length; i++) {
            var fieldName = arguments[i];
            var atLeastOne = false;
            for (j = 0; j < checkboxes.length; j++) {
                if ((checkboxes[j].type == "checkbox" || checkboxes[j].type == "radio")
                        && checkboxes[j].name == fieldName
                        && checkboxes[j].checked == true)
                    atLeastOne = true;
            }
            if (atLeastOne == false) {
                alert("Choose one!!!");
                return false;
            }
        }
    }
    

    也适用于单选按钮,如您所见。

    【讨论】:

      【解决方案2】:

      我对表单提交到的操作做了一个验证方法。

      deliveryTimesInputList 是带有复选框列表值的整数列表。

      @Override
      public void validate() {
      
          if(deliveryTimesInputList == null || deliveryTimesInputList.isEmpty()){
              addFieldError("deliveryTimesInputList", "Du må velge minst et leveringstidspunkt for dette postnummeret");
          }
      
      }
      

      【讨论】:

        【解决方案3】:

        使用以下代码进行struts2 xml验证。复选框List的值存储为字符串。因此,您可以使用requiredstring。

        <field name="someName">
          <field-validator type="requiredstring">
             <message>You need to select at least one option</message>
           </field-validator>
          </field>
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-07-12
          • 2023-03-28
          • 1970-01-01
          • 1970-01-01
          • 2015-10-31
          • 1970-01-01
          相关资源
          最近更新 更多