使用 Jquery 单击按钮时的客户端数据注释验证

Client side Data Annotation validation on a button click using Jquery

我有一个模型,其中包含 Required 属性。是否可以对非提交类型的按钮单击进行数据验证。我确实参考了 this article and 但它没有解决问题。

这是我的模型代码。

 [Required]
 [Display(Name = "Number of beds")]
 public int Beds { get; set; }
 [Required]
 [Display(Name = "Number of Inpatient Beds")]
 public int InpatientBeds { get; set; }

我的看法

@using (Html.BeginForm(new {id = "form1", @class = "form-horizontal" }))
{

<div class="divPanel">
    <div class="row">
        <div class="col-md-3">                
                @Html.LabelFor(m => m.Beds)
                @Html.TextBoxFor(m => m.Beds, new { @class = "form-control", @type = "number"})
                @Html.ValidationMessageFor(m => m.Beds)

        </div>
        <div class="col-md-3">

                @Html.LabelFor(m => m.InpatientBeds)
                @Html.TextBoxFor(m => m.InpatientBeds, new { @class = "form-control", @type = "number"})
                @Html.ValidationMessageFor(m => m.InpatientBeds)
        </div>
<div class="col-md-3">             
            <button type=button  class="btn btn-primary" id="btnCalculateScore" > Calculate Score</button>
        </div>
 </div>
<div class="col-md-3">           
        <button type="submit" class="btn btn-primary" id="btnSaveChanges" data-toggle="modal"><i class="fa fa-share-square-o"></i> Update Status</button>
    </div>
</div>
}

还有我的剧本

$('#btnCalculateScore').on('click', function (evt) {

evt.preventDefault();

if ($('#form1').valid()) {
    //Do Something.
}
}

验证不起作用,即使字段为空,控件也会进入 if 循环?有什么我想念的吗?此外,这种方法是否也会给出通常在提交按钮事件上发生的验证消息?

编辑:

  1. 我添加了一个正常的更新状态按钮,类型为提交,验证工作正常。

  2. 我将 id 添加到我的表单中,以确保视图包含其他表单无关紧要。

我遇到了同样的问题,这似乎为我解决了。

@using (Html.BeginForm(new {id = "form1", @class = "form-horizontal" }))

查看页面源代码后,此代码不会将 ID Form1 附加到您的表单。因此,您的验证不会发生,因为未找到 ID 为 form1 的表单。

相反,假设您的操作是 post 并且您将数据保存在 Action Method Save 和 controller Bed 中,您可以将表单编辑为

@using (Html.BeginForm("Save", "Bed", FormMethod.Post, new { id = "form1",@class = "form-horizontal"}))

这会将 id 参数附加到您的表单(您可以使用 ViewPageSource 检查)并且它应该可以工作。可能有更好的解决方案,但这对我来说没有问题。