2014-12-03 32 views
0

我一直在努力嘗試讓自定義錯誤消息在3種不同情況下正確顯示,當使用jQuery驗證插件。jQuery驗證錯誤消息的條件需要和組

  • 我在哪裏有一個小組,只需要一個小組的成員。
  • 複選框字段的自定義消息。
  • 當有條件地需要字段時顯示錯誤消息。

我已記錄下此帖子:How to show different error messages based on various conditions。這可能是我的問題解決方案的一部分嗎?我也看過Custom error messages for Groups within the jQuery Validation plugin,但它似乎沒有解決只有1名成員被要求的問題,並沒有解決我的問題。

我是新來的jQuery和小提琴,並有一個小提琴不能正常工作。我懷疑它是因爲我沒有鏈接到來自驗證插件包中的Milk和Marketo示例的CSS中使用的圖形。小提琴在http://jsfiddle.net/cloudmech/myvmb95d/23/

這是我正在使用的代碼。

jQuery的:

$(document).ready(function() { 
    $('#00NU00000049YHZ').change(function(){ 
     var checked = $(this).is(':checked'); 
     $('#company_information').toggle(checked); 
     $('#company').prop('disabled', !checked) 
    }).change(); 

    var $CompHdwDon = $('#00NU00000049YHj'), 
    $SchedPickup = $('#00NU00000049YHt'); 

    $('#w2lForm').validate({ 
     debug: true, 
     rules:{ 
      company: { 
       depends: function(element) { 
        var checked = $('#00NU00000049YHZ').is(':checked'); 
        return (checked); 
       minlength: 3 
        } 
       },    
      phone: { 
       require_from_group: [1, '.phone_group'], 
       phoneUS: true, 
      }, 
      Mobile: { 
       require_from_group: [1, '.phone_group'], 
       phoneUS: true, 
      }, 
      CompHdwDon: { 
       required: checked=true 
      },    
      SchedPickup: { 
       required: checked=true 
      },  
     }, 
     messages: { 
      company: { 
       depends: function(element) { 
        var checked = $('#00NU00000049YHZ').is(':checked'); 
        return (checked); 
       required: "Please provide the name of your company" 
       } 
      }, 
      phone_group: { 
       required: "Either your regular or mobile phone is required" 
      }, 
      phone: { 
       required: "Either your regular or mobile phone is required" 
      }, 
      Mobile: { 
       required: "Either your regular or mobile phone is required" 
      }, 
      CompHdwDon: { 
       required: "This box must be checked for us to pick up a donation" 
      },  
      SchedPickup: { 
       required: "This box must be checked to schedule a donation pickup" 
      },  
     }, 
     // the errorPlacement has to take the table layout into account 
     errorPlacement: function(error, element) { 
      var n = element.attr("name"); 
      if (n == "phone" || n == "Mobile") 
       error.appendTo(element.parent().next()); 
      else if (element.is(":radio")) 
       error.appendTo(element.parent().next().next()); 
      else if (element.is(':checkbox')) 
       error.appendTo(element.parent().next()); 
      else 
       error.appendTo(element.parent().next()); 
     }, 
     // set this class to error-labels to indicate valid fields 
     success: function(label) { 
      // set   as text for IE 
      label.html(" ").addClass("checked"); 
     }, 
     highlight: function(element, errorClass) { 
      $(element).parent().next().find("." + errorClass).removeClass("checked"); 
     } 
     // specifying a submitHandler prevents the default submit, good for the demo 
    }); 

}); 

的HTML:

<BODY> 
<div id="page-content-inner" class="resize"> 
<form id="w2lForm" action="https://www.xxxxx.com/servlet/servlet.WebToLead?encoding=UTF-8" method="POST"> 
<input type=hidden name="retURL" value="http://www.google.com"> 
</br> 
<TABLE > 
<TR> 
    <TD class="label">This is for a Company:</TD> 
    <TD class="field"><input id="00NU00000049YHZ" name="00NU00000049YHZ" type="checkbox" value="0" /></TD> 
    <TD class="status"></TD> 
<!-- If is This is for a Company == false, hide line below. If = true, show line below --> 
    <TD class="label" colspan="2"> 
    <div id="company_information"> 
    <label id="cmpnylbl" for="company" class="label" >Company: 
    <input id="company" maxlength="40" name="company" size="20" type="text" class="required" /></div></TD> 
    <TD class="status"></TD> 
</TR> 
<!--- create phone group below and require 1 of the two ---> 
<TR> 
    <TD class="label"><label for="phone">Phone:</label></TD> 
    <TD class="field"><input id="phone" class="phone_group" maxlength="40" name="phone" size="20" type="text" /></TD> 
    <TD class="status"></TD> 
    <TD class="label"><label for="mobile">Mobile:</label></TD> 
    <TD class="field"><input id="mobile" class="phone_group" maxlength="40" name="mobile" size="20" type="text" /></TD> 
    <TD class="status"></TD> 
</TR> 
<TR> 
    <TD class="label">Computer Hardware Donation:</TD> 
    <TD class="field"><input id="00NU00000049YHj" name="00NU00000049YHj" type="checkbox" value="1" class="required" /></TD> 
    <TD class="status"></TD> 
    <TD class="label">Schedule Pickup:</TD> 
    <TD class="field"><input id="00NU00000049YHt" name="00NU00000049YHt" type="checkbox" value="1" class="required" /></TD> 
    <TD class="status"></TD> 
</TR> 
<TR><TD class="field" COLSPAN="4"><input type="submit" name="submit"></TD></TR> 
</TABLE> 
</form> 
</div> 
</BODY> 

的CSS:

body, input, select, textarea { font-family: verdana, arial, helvetica, sans-serif; font-size: 11px; } 
img { 
    border: 0px; 
} 

#resize{ 
    width: 500px; 
} 

.clear { 
    clear: both; 
} 

input { border: 1px solid black; margin-bottom: .5em; } 

input.error { border: 2px solid red; } 

label.error { 
    display: block; 
    color: red; 
    font-style: italic; 
    font-weight: normal; 
    background: url('images/unchecked.gif') no-repeat; 
    padding-left: 16px; 
    margin-left: .3em; 
} 
label.valid { 
    background: url('images/checked.gif') no-repeat; 
    display: block; 
    width: 16px; 
    height: 16px; 
} 

form table td { 
    padding: 5px; 
} 

form table input { 
    width: 200px; 
    padding: 3px; 
    margin: 0px; 
} 

textarea { 
    width: 400px 
} 

td.label { 
    width: 150px; 
} 

tr.required td.label { 
    font-weight: bold; 
    background: url('images/backRequiredGray.gif') no-repeat right 
     center; 
} 


td.field input.error, td.field select.error, tr.errorRow td.field input,tr.errorRow td.field select { 
    border: 2px solid red; 
    background-color: #FFFFD5; 
    margin: 0px; 
    color: red; 
} 

tr td.field div.formError { 
    display: none; 
    color: #FF0000; 
} 

tr.errorRow td.field div.formError { 
    display: block; 
    font-weight: normal; 
} 

#w2lForm .table { 
    border-spacing: 0px; 
    border-collapse: collapse; 
    empty-cells: show; 
} 

#w2lForm .label { 
    padding-top: 2px; 
    padding-right: 8px; 
    vertical-align: top; 
    text-align: right; 
    width: 125px; 
    white-space: nowrap; 
} 

#w2lForm .field { 
    padding-bottom: 10px; 
    white-space: nowrap; 
} 

#w2lForm .status { 
    padding-top: 2px; 
    padding-left: 8px; 
    vertical-align: top; 
    width: 246px; 
    white-space: nowrap; 
} 

#w2lForm .textfield { 
    width: 150px; 
} 

#w2lForm label.error { 
    background:url("images/unchecked.gif") no-repeat 0px 0px; 
    padding-left: 16px; 
    padding-bottom: 2px; 
    font-weight: bold; 
    color: #EA5200; 
} 

#w2lForm label.checked { 
    background:url("images/checked.gif") no-repeat 0px 0px; 
} 

至於最後一個問題,當我得到這一切的工作,我要發佈它使用顯示的servlet。我是否需要在我的jQuery中添加下面的內容,是否需要構建Ajax處理程序或者什麼都不做?我注意到,當servlet的完整URL可用時,它似乎按「原樣」提交。

submitHandler: function(form) { 
    form.submit(); 
} 

修訂的jQuery:

$(document).ready(function() { 

    $('#00NU00000049YHZ').change(function(){ 
     var checked = $(this).is(':checked'); 
     $('#company_information').toggle(checked); 
     $('#company').prop('disabled', !checked) 
    }).change(); 

    $('#00NU00000049YHZ').on('change', function() { // fire on change 
     $('[name="company"]').valid(); // evaluate rules on company 
    }); 


    $('#w2lForm').validate({ 
     debug: true, 

     rules:{ 
      company: { 
       required: { 
        depends: function(element) { 
         return $('#00NU00000049YHZ').is(':checked'); 
        } 
       }, 
       minlength: 3 
      },    
      phone: { 
       require_from_group: [1, '.phone_group'], 
       phoneUS: true, 
      }, 
      Mobile: { 
       require_from_group: [1, '.phone_group'], 
       phoneUS: true, 
      }, 
      "00NU00000049YHj": { 
       required: true 
      },    
      "00NU00000049YHt": { 
       required: true 
      },  
     }, 
     messages: { 
      company: { 
       required: "Please provide the name of your company", 
       minlength: "Please type at least {0} characters" 
      }, 
      phone: { 
       require_from_group: "Either your regular or mobile phone is required" 
      }, 
      Mobile: { 
       require_from_group: "Either your regular or mobile phone is required" 
      }, 
      "00NU00000049YHj": { 
       required: "This box must be checked for us to pick up a donation" 
      },  
      "00NU00000049YHt": { 
       required: "This box must be checked to schedule a donation pickup" 
      },  
     }, 
     // the errorPlacement has to take the table layout into account 
     errorPlacement: function(error, element) { 
      var n = element.attr("name"); 
      if (n == "phone" || n == "Mobile") 
       error.appendTo(element.parent().next()); 
      else if (element.is(":radio")) 
       error.appendTo(element.parent().next().next()); 
      else if (element.is(':checkbox')) 
       error.appendTo(element.parent().next()); 
      else 
       error.appendTo(element.parent().next()); 
     }, 
     // set this class to error-labels to indicate valid fields 
     success: function(label) { 
      // set &nbsp; as text for IE 
      label.html("&nbsp;").addClass("checked"); 
     }, 
     highlight: function(element, errorClass) { 
      $(element).parent().next().find("." + errorClass).removeClass("checked"); 
     } 

    }); 

}); 

回答

4

你的最後一個問題......第一

,當你想改變這個插件的默認行爲時,才需要submitHandler回調函數。默認行爲是表單提交將被阻止,直到所有數據條目都通過驗證,然後它將被提交到form元素的action屬性中的URL。

此代碼基本上是默認的,所以整個這submitHandler是多餘的,可以去掉的.validate() ...

submitHandler: function(form) { 
    form.submit(); // <- already the default behavior 
} 

但是,如果你想通過ajax提交表單,那麼你可以使用它如下...

submitHandler: function(form) { 
    // your ajax function here 
    return false; 
} 

其次,你的代碼是真的在這裏破...

rules:{ 
    company: { 
     depends: function(element) { 
      var checked = $('#00NU00000049YHZ').is(':checked'); 
      return (checked); 
     minlength: 3 
      } 
     }, 
.... 
messages: { 
    company: { 
     depends: function(element) { 
      var checked = $('#00NU00000049YHZ').is(':checked'); 
      return (checked); 
     required: "Please provide the name of your company" 
     } 
    }, 

depends是不是一個規則; depends是一個規則的屬性,只需簡單地切換規則的打開和關閉,並且不能在功能內部浮動鍵:值對。這應該會導致各種錯誤。你會從來沒有dependsmessages裏面,因爲消息不依賴於任何東西......它只是附加到一個規則。

想必,你要根據另一種情況,companyrequired ...

rules:{ 
    company: { 
     required: { 
      depends: function(element) { 
       return $('#00NU00000049YHZ').is(':checked'); 
      } 
     }, 
     minlength: 3 
    }, 
    .... 
}, 
messages: { 
    company: { 
     required: "Please provide the name of your company", 
     minlength: "Please type at least {0} characters" 
    }, 
    .... 
}, 
.... 

第三,這是什麼?

CompHdwDon: { 
    required: checked=true 
},    
SchedPickup: { 
    required: checked=true 
}, 

你不能把checked=true作爲值時required方法的值只能是一個布爾或函數(depends)。

CompHdwDon: { 
    required: true 
},    
SchedPickup: { 
    required: true 
}, 

最後,require_from_group方法/規則將創建一個條件,即使你只想要一個場淘汰一批是required,將出現在所有的人都錯誤消息。 The solution is to use the groups option, which will simply group all messages for this particular group of fields into one。使用errorPlacement選項可以實現郵件的準確放置。


編輯

你的代碼,例如。

rules: { 
    Mobile: { 
     require_from_group: [1, '.phone_group'], 
     phoneUS: true 
    }, 
}, 
messages: { 
    Mobile: { 
     required: "Either your regular or mobile phone is required" 
    }, 
} 

的方法在你的rules不匹配messages下的方法......你能留下一些了,但你不能添加任何不存在的。

messages下的相應key:value對需要匹配...

messages: { 
    .... 
    Mobile: { 
     require_from_group: "Either your regular or mobile phone is required" 
    }, 
    .... 

編輯2:

CompHdwDon: { // <- this should match the NAME of the field! 
    required: true 
}, 

此代碼是即使什麼也不做,因爲你有沒有現場name="CompHdwDon"。它只有出現才能工作,因爲您在複選框上有class="required"。在這種情況下,插件使用requiredclass來設置規則。在.validate()內聲明規則或聲明它們是內聯的,但不需要同時執行這兩個規則。

改變了...

<TD class="label">Computer Hardware Donation:</TD> 
<TD class="field"><input id="00NU00000049YHj" name="00NU00000049YHj" type="checkbox" value="1" class="required" /></TD> 

這個...

<TD class="label">Computer Hardware Donation:</TD> 
<TD class="field"><input id="CompHdwDon" name="CompHdwDon" type="checkbox" value="1" /></TD> 

編輯3

highlight: function(element, errorClass) { 
    $(element).parent().next().find("." + errorClass).removeClass("checked"); 
} 

你並不需要附加一個時期到errorClass對象。它已經內置。當使用highlight時,通常也需要unhighlight

你也不應該需要.find(errorClass),因爲這個類總是觸發,而highlight只在字段無效時觸發。另請注意,highlight僅針對正在評估的特定字段。

highlight: function(element, errorClass) { 
    $(element).parent().next().removeClass("checked"); 
}, 
unhighlight: function(element, errorClass) { 
    $(element).parent().next().addClass("checked"); 
} 

編輯4

要立即觸發另一場錯誤消息時點擊複選框意味着我們需要一個事件處理程序。然後,我們簡單地啓動.valid()方法來評估該領域的規則。

$('#00NU00000049YHZ').on('change', function() { // fire on checkbox change 
    $('[name="company"]').valid(); // evaluate rules on company 
}); 

或者這...

// assuming your existing change handler is already working... 
$('#00NU00000049YHZ').change(function(){ 
    var checked = $(this).is(':checked'); 
    $('#company_information').toggle(checked); 
    $('#company').prop('disabled', !checked); 
    $('[name="company"]').valid(); // evaluate rules on company 
}).change(); 

爲安全起見,把這個change處理您的來電.validate()後。

+0

偉大的答覆斯帕奇。根據是否選中複選框,公司字段是必需的。 'CompHdwDon'是一個需要檢查的複選框。 'SchedPickup'一樣。我無法獲得自定義消息出現在本組中,只有標準的消息才能控制您的位置。 – crmprogdev 2014-12-03 17:25:57

+0

@crmprogdev,當你不使用'required'規則時,你不能爲'required'設置一個自定義消息。當您使用'required_from_group'規則時,您將自定義消息設置爲'require_from_group'。看到我編輯的答案。慢慢來,慢下來... – Sparky 2014-12-03 17:45:04

+0

一直在努力解決這個問題。大聲笑! '.phone_group'是一個CSS類,不是使用add group方法創建的組。文檔在這方面令人困惑。 'require_from_group'最終解決了羣組的自定義消息問題!進展! :)顯示時,仍然會獲得複選框的標準消息,並且公司字段上的切換框沒有消息。 – crmprogdev 2014-12-03 17:53:37