我已经成功地用 HTML、CSS 和 JS(依赖项:jQuery 和验证)为我的网站制作了一个有效的 jQuery.validation 表单。问题是当我在一个干净的 ASP.NET Core Web 项目中并且我使用完全相同的代码时,它似乎没有在 JavaScript 中使用我的自定义验证参数
验证适用于所有情况。但是,我的习惯[options]
对于 .validate([options])
似乎不适用于 ASP.NET Core
工作代码示例:JSFiddle
HTML:
<form method="post">
<fieldset>
<div class="master">
<input name="name" id="name" placeholder="Name" minlength="2" maxlength="40" required />
</div>
<div class="master">
<input name="email" id="email" placeholder="Email Address" type="email" required />
</div>
<div class="master">
<input name="company" placeholder="Company Name" />
</div>
<div class="master">
<input name="website" placeholder="Website" type="url" required />
</div>
<button type="submit">Next</button>
</fieldset>
</form>
CSS:
.master {
padding: 10px;
background-color: white;
}
.has-error {
background-color: red;
}
.has-success {
background-color: green;
}
JS:
$('form').validate({
// This disables the default validation notifications to the user.
// Instead I'll be using CSS colors to notify users of valid or invalid fields
errorPlacement: function (error, element) { },
// Invalid field produces a red-background in parent element
highlight: function(element) {
$(element).parent().addClass('has-error').removeClass('has-success');
},
// Valid field produces a green-background in parent element
unhighlight: function(element) {
$(element).parent().removeClass('has-error').addClass('has-success');
}
});
我的 JavaScript .validate([options])
做三件事:
- 删除 jQuery.validation 的默认通知选项
- 如果
<field>
为无效,父元素背景颜色为红色 - 如果
<field>
是VALID,父元素background-color是green
注意:
- 将我的 ASP.NET Core (1.1) 更新到最新的稳定版本
- 降级到 ASP.NET Core 1.0 进行测试
- 通过 bower、本地和 CDN(用于测试)添加了最新的 jQuery
- 添加了最新的通过 bower、本地和 CDN 验证(用于测试)
- 根据 Validate 的网站,必须使用某些版本的 jQuery 以实现兼容性。我通过 bower、本地和 CDN 测试了所有版本
- 制作了一个原始的 HTML、CSS 和 JS 版本,在 JSFiddle、CodePen 和本地中删除了所有内容(包括)。 一切都很完美但在 ASP 项目中却不是。
- 外部或内联 JavaScript,没有变化。
我的结论: 验证适用于所有情况,这意味着 ASP.NET Core 应用程序和纯 HTML - CSS - JS 都具有正确的功能验证。
唯一不起作用的是当我提供 [options]
时在我的 $('form').validate([options]);
在 ASP.NET Core 应用程序中。我不确定为什么我的选项没有被使用。
.validate([options]) 上的官方 jQuery.validate 页面
最佳答案
我解决了这个问题。它与 jQuery.validate([option]
) 对象属性有关:success
它直接与另外两个属性冲突:highlight
和 unhighlight
例如:
$('form').validate({
errorPlacement: function (error, element) { },
highlight: function (element) {
// Do stuff
},
unhighlight: function (element) {
// Do stuff
}
success: function (element) {
// Do stuff
}
});
success
属性完全使用不同的方式通过工具提示通知用户无效字段。而 highlight
和 unhighlight
有更多的自定义方式供开发人员进行更多控制。
在 ASP.NET Core 中,由于 jQuery.validate 随每个 ASP.NET Core Web 应用程序一起提供,它应用自己的 success
属性作为构建中某处脚手架的一部分。
我解决这个问题的方法是最后显式调用我的 JS 脚本,并在 success
函数中放置一个对任何函数的回调。
关于javascript - jQuery.validate 不适用于 ASP.NET Core,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42428545/