我正在尝试实现本文中提到的代码。换句话说,我正在尝试在条款和条件复选框上实施不显眼的验证。如果用户没有选择复选框,那么输入应该被标记为无效。
这是服务器端验证器代码,我已添加:
/// <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>
有任何想法吗?我错过了一步吗?这让我如厕!
在此先感谢