jquery - 如何在 ASP.Net MVC 中使用单选按钮的自定义消息在客户端添加必填字段验证?
问题描述
如何在 ASP.Net MVC 中使用单选按钮的自定义消息在客户端添加必填字段验证?
<div class="form-group">
<div class="col-sm-4 control-label">
<label class="hthin" asp-for="IsGuidance"></label>
<label class="hthin">Coach: @Model.GuideName</label>
</div>
<div class="col-sm-3 checkbox-inline">
@Html.RadioButtonFor(model => model.IsGuidance, 1, new { @Id = "IsGuidanceYes" })
<label class="hthin" for="IsGuidanceYes">Yes</label>
@Html.RadioButtonFor(model => model.IsGuidance, 0, new { @Id = "IsGuidanceNo" })
<label class="hthin" for="IsGuidanceNo">No</label>
<span asp-validation-for="IsGuidance" class="text-danger"></span>
</div>
</div>
我写了一个 Jquery 文件:
$('input[name="IsGuidance"]').rules("add",
{
required: true,
messages: {
required: "Please select Yes or No"
}
});
虽然,这不是验证(或)验证消息未显示在 UI 上。
解决方案
我在这个小提琴中进行了测试,您的客户端验证规则似乎工作正常。您应该做的是使用内部函数或内部函数放置自定义errorPlacement
错误消息:errorElement
errorContainer
validate()
jQuery(内部$(document).ready()
)
// hint: you can use $('form') selector
// using errorPlacement
$('#form').validate({
errorPlacement: function (error, element) {
error.appendTo($('#errorPlaceholderName'));
}
});
// alternative with errorElement & errorLabelContainer
$('#form').validate({
errorElement: 'span',
errorLabelContainer: '.text-danger'
});
您也可以尝试放置服务器端 viewmodel 属性验证属性:
模型
[Required(ErrorMessage = "IsGuidance is required")]
public int? IsGuidance { get; set; }
注意: rules('add', ...)
方法必须遵循validate()
才能启用客户端验证,如在类似问题中给出的。
参考:jQuery 验证插件
推荐阅读
- ruby - 为什么我的绘图方法中存在错误(自动归因?)
- c - 取消引用 int 指针与 char 指针
- html - 冻结在没有 JavaScript 的情况下同时使用水平和垂直滚动的 HTML 表格的前两列和最后一列
- c# - 使用 Selenium C# 测试经过身份验证的网站
- android - 如何将 MutableMap 从活动发送到另一个有意图的活动
- asp.net-core - 从 ASP.Net Core 应用程序向 PowerFlow 发送数据
- mysql - 将数据插入 MySQL 时如何在单词末尾添加空格?
- typescript - TypeScript 的 C 开发人员简介
- c - 为什么调用 __pure__ 函数但不使用答案?
- sql - 如何编写 postgresql 查询以在数据库中查找某人的表弟?