MVC4 JQuery验证无法验证非必填字段

时间:2014-02-14 09:11:19

标签: jquery asp.net-mvc validation asp.net-mvc-4

如何获取MVC4 / JQuery Validate以将验证应用于可空属性?

例如,我在模型中有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编辑器应验证只能输入数字,而是允许输入字母等。计数器编辑器会阻止输入字母。

我还尝试使用正则表达式来验证非必填字段,但这与数字验证一样被忽略。

有什么想法吗?

1 个答案:

答案 0 :(得分: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.

之类的消息