2
有我見過關於這幾個其他職位:MVC3 Unobtrusive Validation Extension;條款和條件複選框
MVC unobtrusive validation on checkbox not working
MVC3: make checkbox required via jQuery validate?
但我實現了他們並不能完全弄清楚,爲什麼我的驗證ISN 「T正常工作:
屬性:
[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>
服務器端驗證工作(雖然它返回默認錯誤消息,而不是重寫的),但客戶端不是 - 我只是沒有收到任何消息,但一切正常執行?任何人都能看到我的問題?