【问题标题】:jQuery validate with single element and rulesjQuery 使用单个元素和规则进行验证
【发布时间】:2012-10-14 12:01:22
【问题描述】:

作为更大的 jQuery 验证表单的一部分,我有一些输入只需要在按下按钮时进行验证。例如将项目输入到列表中:

<form class="validate">
    // ......
      validated form elements on submit
    // ......

    <select multiple="multiple" id="itemList" size="5"><select>
    <input type="text" id="newItem" name="newItem"/>
    <button type="button" id="addItem">add</button>

    // ......
      validated form elements on submit
    // ......
    <button type="submit">Submit Form</button>
</form>

<script>
    $(document).on("click", "#addItem", function(e){
       if( $("form.validate").validate({}).element("#newItem") ){
           //Code to add valid item to the list
       }
   });
</script>

我不想使用输入的类作为分配规则的一种方式,因为这意味着它将作为主表单的一部分进行验证,但是如果我以 $([form]) 的形式调用验证。 validate({rules..}).element([element]) 他们被忽略了。

我可以让它工作的唯一方法是在验证之前使用规则(“添加”,规则),之后使用规则(“删除”,规则)。

<script>
    $(document).on("click", "#addItem", function(e){
        $("#newItem").rules("add", {
            required: true,
            minlength: 2,
            messages: {
               required: "Required input",
               minlength: jQuery.format("Please, at least {0} characters are necessary")
            }
        });

        $("form.validate").validate().element("#newItem");

        $("#newItem").rules("remove");
    });
</script>

然而,这似乎很不雅,所以如果有人能告诉我哪里出错了,那就太好了:)

【问题讨论】:

  • 如果要检查表单是否有效,为什么要检查 if( $("form.validate").validate({}).element("#newItem") )使用 $("form.validate").valid() 这个方法返回真假,另一种返回验证对象。
  • @prog-mania 此时我不需要知道整个表单是否有效,我只想验证用于填充其他元素的单个输入形式。

标签: jquery forms jquery-validate


【解决方案1】:
<script>
    $(document).on("click", "#addItem", function(e){
       var _validateSingleField=$('form.validate').validate().element('#newItem');

       if(_validateSingleField){
           //Code to add valid item to the list
       }
   });
</script>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多