【发布时间】:2011-10-18 21:38:21
【问题描述】:
我正在尝试实现this post 中提到的代码。换句话说,我正在尝试在条款和条件复选框上实施不显眼的验证。如果用户没有选择复选框,那么输入应该被标记为无效。
这是我添加的服务器端验证器代码:
/// <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
【问题讨论】:
-
您不能只使用
[Requred]属性而不是创建自己的MustBeTrueAttribute吗?
标签: asp.net-mvc-3 razor unobtrusive-javascript unobtrusive-validation