2014-02-14 141 views
1

如何獲得MVC4/JQuery驗證將驗證應用於可爲空的屬性?MVC4 JQuery驗證無法驗證非必填字段

比如我在模型2個數值屬性:

[Required] 
    public int Counter { get; set; } 

    public int? CounterNonRequired { get; set; } 

這剃刀代碼:

<div class="editor-field"> 
    @Html.EditorFor(model => model.Counter) 
    @Html.ValidationMessageFor(model => model.Counter) 
</div> 
<div class="editor-field"> 
    @Html.EditorFor(model => model.CounterNonRequired) 
    @Html.ValidationMessageFor(model => model.CounterNonRequired) 
</div> 

這將產生以下HTML:

<div class="editor-field"> 
    <input class="text-box single-line" 
      data-val="true" 
      data-val-number="The field Counter must be a number." 
      data-val-required="The Counter field is required." 
      id="Counter" 
      name="Counter" 
      type="number" 
      value=""> 
    <span class="field-validation-valid" 
      data-valmsg-for="Counter" 
      data-valmsg-replace="true"> 
    </span> 
</div> 
<div class="editor-field"> 
    <input class="text-box single-line valid" 
      data-val="true" 
      data-val-number="The field CounterNonRequired must be a number." 
      id="CounterNonRequired" 
      name="CounterNonRequired" 
      type="number" 
      value=""> 
    <span class="field-validation-valid" 
      data-valmsg-for="CounterNonRequired" 
      data-valmsg-replace="true"> 
    </span> 
</div> 

的CounterNonRequired編輯器應該驗證只有數字可以輸入,但是它允許字母e tc。計數器編輯器可防止輸入字母。

我也嘗試使用正則表達式來驗證非必填字段,但這與數字驗證相同的方式被忽略。

有什麼想法?

回答

0

嘗試這樣,

查看

@using (Html.BeginForm("Page", "Controller", FormMethod.Post, new { id = "FrmIndex" })) 
{ 
    <div> 
     @Html.TextBoxFor(model => model.Counter) 
     @Html.ValidationMessageFor(model => model.Counter) 
    </div> 
    <div> 
     @Html.LabelFor(m => m.CounterNonRequired) 
     @Html.EditorFor(m => m.CounterNonRequired) 
     @Html.ValidationMessageFor(m => m.CounterNonRequired) 
    </div> 
    <input type="submit" value="Save" style="float: left;" id="btnSave" title="btn" name="ButtonType" /> 
} 

在視圖模型

public class RegisterModel 
{ 
    [Required] 
    public int Counter { get; set; } 

    public int? CounterNonRequired { get; set; } 
} 

腳本使用

<script src="~/Script/Jquery-1.8.1.min.js" type="text/javascript"></script> 
<script src="@Url.Content("~/Script/jquery.validate.min.js")" type="text/javascript"></script> 
<script src="@Url.Content("~/Script/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script> 

而且它不允許CounterNonRequired文本框中信,如果你在文本框中輸入字母它火的消息像The field CounterNonRequired must be a number.

+0

我用它列入了MVC模板的jQuery 1.8.2。就像在你的例子中,我回到了1.8.1,但它仍然不起作用。你使用的是什麼版本的jquery.validate? – ChaoticNadirs

+0

@ChaoticNadirs版本1.8.0 – Jaimin