0

我有一个使用数据注释进行验证的 ASP.NET MVC 站点,我想获得“免费”客户端验证。大多数简单的工作都很好,而 Foolproof 可以帮助我处理更复杂的场景。到目前为止一切都很好。

但是,我也在使用 Bootstrap,我想利用 Bootstrap 的 UI 进行验证。我对 Bootstrap 不是很有经验,所以请原谅我在这里可能有的任何不好的假设。(显然我错了,Bootstrap 在这个问题中并不重要。)

但是,我想将 HTML5 验证与浏览器支持联系起来。具体来说,我想为所有客户端验证消息使用小弹出窗口。

我在这里创建了一个 jsFiddle 示例,解释了我想要什么以及来自:https ://jsfiddle.net/4nftdufu/

我想看到的行为由第一种形式 ( Foo) 显示。

<form class="form-inline">
    <div class="form-group">
        <input type="text" class="form-control" id="inputFoo" placeholder="Type Foo Here" required>
    </div>
    <button type="submit" class="btn btn-primary">Submit Foo</button>
</form>

第二种形式 ( Bar) 本质上是我来自的地方。请注意,我在这里挂钩了一些 Bootstrap 验证行为(我在博客文章或其他一些 SO 问题的某处在线发现了 CSS)。最终,这不是我想要的行为,而且我没有花任何时间清理这种不完美的集成。

<form class="form-inline">
    <div class="form-group">
        <input class="form-control input-validation-error" data-val="true" data-val-required="Required" id="inputBar" name="inputBar" placeholder="Enter Bar here" type="text" value="" aria-required="true" aria-describedby="Bar-error" aria-invalid="true">
        <p class="help-block"><span class="field-validation-valid" data-valmsg-for="inputBar" data-valmsg-replace="true"></span></p>
    </div>
    <button type="submit" class="btn btn-primary">Submit Bar</button>
</form>

最终,我的问题是:

在受支持的浏览器中,如何让我的 Data Annotations + jQuery Unobtrusive-driven 验证挂钩到所有验证消息的这些 HTML5 弹出窗口?

4

1 回答 1

1

MVC's client side validation using the jquery.validate.js and jquery.validate.unobtrusive.js files and HTML-5 validation do not play well together. The jquery.validate.js file in fact adds the novalidate attribute to your <form> element to disable HTML-5 validation using the following code

// Add novalidate tag if HTML5.
this.attr( "novalidate", "novalidate" );

If you want your messages to look like the browsers callouts, then you can always use css to style the element generated by @Html.ValidationMessageFor(). When a form control is invalid, a class="field-validation-error" is added to the element which can be used for styling (adding color, borders, using the ::after pseudo selector to add arrows etc)

于 2017-09-19T04:20:56.603 回答