我还看过其他一些关于此的帖子:
但是我已经实现了它们并且不能完全弄清楚为什么我的验证不能正常工作:
属性:
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public sealed class MustBeTrueAttribute : ValidationAttribute, IClientValidatable {
public override bool IsValid(object value) {
return value != null && (bool)value;
}
public override string FormatErrorMessage(string name) {
return string.Format("The {0} field must be true.", name);
}
#region Implementation of IClientValidatable
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context) {
yield return new ModelClientValidationRule {
ErrorMessage = string.IsNullOrEmpty(ErrorMessage) ? FormatErrorMessage(metadata.DisplayName) : ErrorMessage,
ValidationType = "mustbetrue"
};
}
#endregion
}
适配器扩展:
// Unobtrusive validation extras
$.validator.unobtrusive.adapters.addBool("mustbetrue", function (options) {
//b-required for checkboxes
if (options.element.tagName.toUpperCase() == "INPUT" && options.element.type.toUpperCase() == "CHECKBOX") {
options.rules["required"] = true;
if (options.message) {
options.messages["required"] = options.message;
}
}
});
模型属性:
[Display(Name = "I agree to RustyShark's Terms of Use")]
[MustBeTrueAttribute(ErrorMessage = "You must agree to the Terms of Use")]
public bool AgreeToTerms { get; set; }
看法:
<div class="formField">
<div class="label">
@Html.LabelFor(m => m.AgreeToTerms); @Html.ActionLink("view here", "TermsOfUse", "Home", null, new { target = "_blank" }).
</div>
<div class="input">
@Html.CheckBoxFor(m => m.AgreeToTerms)
</div>
@Html.ValidationMessageFor(m => m.AgreeToTerms)
</div>
呈现以下 HTML:
<div class="formField">
<div class="label">
<label for="AgreeToTerms">I agree to RustyShark's Terms of Use</label>; <a href="/Home/TermsOfUse" target="_blank">view here</a>.
</div>
<div class="input">
<input data-val="true" data-val-mustbetrue="You must agree to the Terms of Use" data-val-required="The I agree to RustyShark&#39;s Terms of Use field is required." id="AgreeToTerms" name="AgreeToTerms" type="checkbox" value="true" class="valid"><input name="AgreeToTerms" type="hidden" value="false">
</div>
<span class="field-validation-valid" data-valmsg-for="AgreeToTerms" data-valmsg-replace="true"></span>
</div>
服务器端验证正在工作(虽然它返回的是默认错误消息,而不是被覆盖的错误消息),但客户端没有 - 我只是没有收到任何消息,但一切都在正确执行?谁能看到我的问题?