提问人:Sniffer 提问时间:8/3/2011 最后编辑:CommunitySniffer 更新时间:11/5/2019 访问量:27195
复选框上的 MVC 非侵入式验证不起作用
MVC unobtrusive validation on checkbox not working
问:
我正在尝试实现本文中提到的代码。换句话说,我正在尝试在条款和条件复选框上实现不显眼的验证。如果用户尚未选中该复选框,则应将输入标记为无效。
这是服务器端的验证器代码,我添加了:
/// <summary>
/// Validation attribute that demands that a boolean value must be true.
/// </summary>
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
public class MustBeTrueAttribute : ValidationAttribute
{
public override bool IsValid(object value)
{
return value != null && value is bool && (bool)value;
}
}
这是模型
[MustBeTrue(ErrorMessage = "You must accept the terms and conditions")]
[DisplayName("Accept terms and conditions")]
public bool AcceptsTerms { get; set; }
这是我的观点:
@Html.EditorFor(x => x.AcceptTermsAndConditions)
@Html.LabelFor(x => x.AcceptTermsAndConditions)
@Html.ValidationMessageFor(x => x.AcceptTermsAndConditions)
这是我用来附加验证器客户端的jQuery:
$.validator.unobtrusive.adapters.addBool("mustbetrue", "required");
但是,客户端脚本似乎并没有启动。每当我按下提交按钮时,对其他字段的验证都会正常启动,但条款和条件的验证似乎没有启动。这是我单击提交按钮后代码在 Firebug 中的样子。
<input type="checkbox" value="true" name="AcceptTermsAndConditions" id="AcceptTermsAndConditions" data-val-required="The I confirm that I am authorised to join this website and I accept the terms and conditions field is required." data-val="true" class="check-box">
<input type="hidden" value="false" name="AcceptTermsAndConditions">
<label for="AcceptTermsAndConditions">I confirm that I am authorised to join this website and I accept the terms and conditions</label>
<span data-valmsg-replace="true" data-valmsg-for="AcceptTermsAndConditions" class="field-validation-valid"></span>
有什么想法吗?我错过了一步吗?这让我如厕!
提前致谢 S
答:
您需要在自定义属性上实现 IClientValidatable,以便将客户端注册的适配器名称与此属性相关联:mustbetrue
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
public class MustBeTrueAttribute : ValidationAttribute, IClientValidatable
{
public override bool IsValid(object value)
{
return value != null && value is bool && (bool)value;
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
yield return new ModelClientValidationRule
{
ErrorMessage = this.ErrorMessage,
ValidationType = "mustbetrue"
};
}
}
更新:
完整的工作示例。
型:
public class MyViewModel
{
[MustBeTrue(ErrorMessage = "You must accept the terms and conditions")]
[DisplayName("Accept terms and conditions")]
public bool AcceptsTerms { get; set; }
}
控制器:
public class HomeController : Controller
{
public ActionResult Index()
{
var model = new MyViewModel();
return View(model);
}
[HttpPost]
public ActionResult Index(MyViewModel model)
{
return View(model);
}
}
视图:
@model MyViewModel
<script src="@Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>
<script type="text/javascript">
$.validator.unobtrusive.adapters.addBool("mustbetrue", "required");
</script>
@using (Html.BeginForm())
{
@Html.CheckBoxFor(x => x.AcceptsTerms)
@Html.LabelFor(x => x.AcceptsTerms)
@Html.ValidationMessageFor(x => x.AcceptsTerms)
<input type="submit" value="OK" />
}
评论
ErrorMessageResourceType
ErrorMessageResourceName
ErrorMessage = FormatErrorMessage(metadata.DisplayName),
$.validator.unobtrusive.adapters.addBool("mustbetrue", "required");
<script type="text/javascript">
$(document).ready(function () {
嗅探器
除了实现Darin的解决方案外,还需要修改文件。在此文件中,必须添加“mustbetrue”验证方法,如下所示:jquery.validate.unobtrusive.js
$jQval.addMethod("mustbetrue", function (value, element, param) {
// check if dependency is met
if (!this.depend(param, element))
return "dependency-mismatch";
return element.checked;
});
然后(我一开始忘了添加这个),您还必须将以下内容添加到:jquery.validate.unobtrusive.js
adapters.add("mustbetrue", function (options) {
setValidationValues(options, "mustbetrue", true);
});
辅导员本
评论
$.validator.addMethod()
$.validator.unobtrusive.adapters.add()
我不确定为什么这对我不起作用,但我选择使用您的代码并做一些稍微不同的事情。
在我的 JavaScript 加载中,我添加了以下内容,如果您选中该复选框并取消选中它,这将使该复选框触发非侵入性验证。此外,如果您提交表格。
$(function () {
$(".checkboxonblurenabled").change(function () {
$('form').validate().element(this);
});
});
您还需要将 CSS 类添加到复选框中,如下所示。
@Html.CheckBoxFor(model => model.AgreeToPrivacyPolicy, new { @class = "checkboxonblurenabled"})
因此,我们现在需要连接模型并放入 out 类来处理服务器端验证(我从上面重用),但稍微改变了不显眼性。
下面是扩展 IClientValidate 的 customer 属性,如上例所示...
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
public class MustBeTrueAttribute : ValidationAttribute, IClientValidatable
{
public override bool IsValid(object value)
{
return value != null && value is bool && (bool)value;
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
yield return new ModelClientValidationRule
{
ErrorMessage = this.ErrorMessage,
ValidationType = "mustbetrue"
};
}
}
在模型中,对象属性设置所需的属性表示法
[MustBeTrue(ErrorMessage = "Confirm you have read and agree to our privacy policy")]
[Display(Name = "Privacy policy")]
public bool AgreeToPrivacyPolicy { get; set; }
好了,我们准备加入 JavaScript。
(function ($) {
/*
START CHECK MUST BE TRUE - UNOBTRUSIVE JAVASCRIPT
START CHECK MUST BE TRUE - UNOBTRUSIVE JAVASCRIPT
START CHECK MUST BE TRUE - UNOBTRUSIVE JAVASCRIPT
*/
jQuery.validator.unobtrusive.adapters.add("mustbetrue", ['maxint'], function (options) {
options.rules["mustbetrue"] = options.params;
options.messages["mustbetrue"] = options.message;
});
jQuery.validator.addMethod("mustbetrue", function (value, element, params) {
if ($(element).is(':checked')) {
return true;
}
else {
return false;
}
});
/*
START CHECK MAX INT - UNOBTRUSIVE JAVASCRIPT
START CHECK MAX INT - UNOBTRUSIVE JAVASCRIPT
START CHECK MAX INT - UNOBTRUSIVE JAVASCRIPT
*/
} (jQuery));
是什么让它工作,是......井。在尝试执行上述建议的答案后查看 HTML 标记后,我的值全部设置为 true,但我选中的复选框为 false。因此,我决定让jQuery使用IsChecked来解决它
评论
对于那些这些解决方案都不起作用的人:
我正在使用 .Net Framework 4 和最新的 jquery 验证脚本文件来使用 Razor MVC 4。
在客户端和服务器端实现自定义属性验证后,它仍然不起作用。无论如何,我的表格正在发布。
所以这里有一个问题: JQuery 验证脚本的默认设置是忽略隐藏的标签,其中隐藏是 http://api.jquery.com/hidden-selector/,这通常不会成为问题,但我使用的 @Html.CheckBoxFor 样式是使用 CSS3 样式自定义的,该样式将显示更改为 none,并显示复选框的自定义图像,因此它永远不会在复选框上执行验证规则。
我的解决方法是在自定义客户端验证规则声明之前添加以下行:
$.validator.defaults.ignore = "";
它的作用是覆盖当前页面中所有验证的忽略设置,请注意,现在它也可以对隐藏字段执行验证(副作用)。
评论
<script>
$(function () {
$('#btnconfirm').click(function () {
if ($("#chk").attr('checked') !== undefined ){
return true;
}
else {
alert("Please Select Checkbox ");
return false;
}
});
});
</script>
<div style="float: left">
<input type="checkbox" name="chk" id="chk" />
I read and accept the terms and Conditions of registration
</div>
<input type="submit" value="Confirm" id="btnconfirm" />
/// <summary>
/// Summary : -CheckBox for or input type check required validation is not working the root cause and solution as follows
///
/// Problem :
/// The key to this problem lies in interpretation of jQuery validation 'required' rule. I digged a little and find a specific code inside a jquery.validate.unobtrusive.js file:
/// adapters.add("required", function (options) {
/// if (options.element.tagName.toUpperCase() !== "INPUT" || options.element.type.toUpperCase() !== "CHECKBOX") {
/// setValidationValues(options, "required", true);
/// }
/// });
///
/// Fix: (Jquery script fix at page level added in to check box required area)
/// jQuery.validator.unobtrusive.adapters.add("brequired", function (options) {
/// if (options.element.tagName.toUpperCase() == "INPUT" && options.element.type.toUpperCase() == "CHECKBOX") {
/// options.rules["required"] = true;
/// if (options.message) {
/// options.messages["required"] = options.message;
/// }
/// Fix : (C# Code for MVC validation)
/// You can see it inherits from common RequiredAttribute. Moreover it implements IClientValidateable. This is to make assure that rule will be propagated to client side (jQuery validation) as well.
///
/// Annotation example :
/// [BooleanRequired]
/// public bool iAgree { get; set' }
///
/// </summary>
public class BooleanRequired : RequiredAttribute, IClientValidatable
{
public BooleanRequired()
{
}
public override bool IsValid(object value)
{
return value != null && (bool)value == true;
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
return new ModelClientValidationRule[] { new ModelClientValidationRule() { ValidationType = "brequired", ErrorMessage = this.ErrorMessage } };
}
}
评论
[Requred]
MustBeTrueAttribute