// 錯誤示範 $("#form1").validate({ rules: { txtName: "required", txtAge: { required: true, min: 18 } }, messages: { required: "*必填欄位", min: jQuery.validator.format("*年齡須大於{0}") } });在試客戶端驗證時碰到的問題
上面的程式完全沒有反應,但如果改成
// solution 2 $("#form1").validate(); $("#txtName").rules("add", { required: true, messages: { required: "*必填欄位" } }); $("#txtAge").rules("add", { required: true, min: 18, messages: { required: "*必填欄位", min: jQuery.validator.format("*年齡須大於{0}") } });就可行(注意,這個寫法 form.validate(...)一定要在加 rule 進來之前)。
View 部分如下
@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { id = "form1", @class = "form1", name = "form1" })) { <div class="bs-callout bs-callout-primary"> <h4>Person info form</h4> <p>Plz fill in the personal info and press submit btn to send data back.</p> </div> <div class="form-group buffer-bottom"> <div class="input-group"> <span class="input-group-addon same-width-iga">Name</span> @Html.EditorFor(m => m.Name, new { htmlAttributes = new { placeholder = "Andy", @class = "form-control", id = "txtName" } }) </div> </div> <div class="form-group buffer-bottom"> <div class="input-group"> <span class="input-group-addon same-width-iga">Age</span> @Html.EditorFor(m => m.Age, new { htmlAttributes = new { placeholder = 18, @class = "form-control", id = "txtAge" } }) </div> </div> <button class="btn btn-default buffer-right">Cancel</button><button class="btn btn-primary" id="btnSubmit">Submit</button> }
莫名地找了半天才發現 原因
所以
所以山不轉路轉,把 validate 參數的部分配合 model 改掉
$("#form1").validate({ rules: { Name: "required", Age: { required: true, min: 18 } }, messages: { required: "*必填欄位", min: jQuery.validator.format("*年齡須大於{0}") } });
結果問題在於我的想法是錯的,在參數這部分 message 還是必須要個別指定給 input 所以是
$("#form1").validate({ rules: { Name: "required", Age: { required: true, min: 18 } }, messages: { Name: { required: "*必填欄位" }, Age: { required: "*必填欄位", min: jQuery.validator.format("*年齡須大於{0}") } } });
終於對了
可是我之所以不想用 solution 2 就是希望整個專案的同樣驗證規則只要一份客製訊息就好啊! 參考
$("#form1").validate({ rules: { Name: "required", Age: { required: true, min: 18 } } }); $.extend($.validator.messages, { required: "*必填欄位", min: $.validator.format("*年齡須大於{0}") });改成這樣即可
如果你希望驗證時不要送出可以用 form 的 valid() 就好
先把 button(或 input) 改成 type button,避免它送出
<button class="btn btn-primary" id="btnSubmit" type="button">Submit</button>
然後用
$("#btnSubmit").click(function () { $("#form1").valid(); });就行了
如果你需要 client 端客製規則,參考
如果你要完整專案 GitHub
沒有留言:
張貼留言