首页 > 解决方案 > 如何在 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 上。

标签: jqueryasp.net-mvc

解决方案


我在这个小提琴中进行了测试,您的客户端验证规则似乎工作正常。您应该做的是使用内部函数或内部函数放置自定义errorPlacement错误消息:errorElementerrorContainervalidate()

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 验证插件


推荐阅读