使用数据注释强制模型的布尔值为true

这里的问题很简单(我想)。

我的表格底部有一个复选框,用户必须同意条款和条件。 如果用户没有选中该框,我想在我的validation摘要中显示一条错误消息以及其他表单错误。

我将此添加到我的视图模型中:

[Required] [Range(1, 1, ErrorMessage = "You must agree to the Terms and Conditions")] public bool AgreeTerms { get; set; } 

但那没用。

是否有一种简单的方法可以使用数据注释强制值为true?

 using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Threading.Tasks; using System.Web.Mvc; namespace Checked.Entitites { public class BooleanRequiredAttribute : ValidationAttribute, IClientValidatable { public override bool IsValid(object value) { return value != null && (bool)value == true; } public IEnumerable GetClientValidationRules(ModelMetadata metadata, ControllerContext context) { //return new ModelClientValidationRule[] { new ModelClientValidationRule() { ValidationType = "booleanrequired", ErrorMessage = this.ErrorMessage } }; yield return new ModelClientValidationRule() { ValidationType = "booleanrequired", ErrorMessage = this.ErrorMessageString }; } } } 

您可以编写已经提到的自定义validation属性。 如果您正在进行客户端validation,则需要编写自定义javascript以启用不显眼的validationfunction。 例如,如果您使用jQuery:

 // extend jquery unobtrusive validation (function ($) { // add the validator for the boolean attribute $.validator.addMethod( "booleanrequired", function (value, element, params) { // value: the value entered into the input // element: the element being validated // params: the parameters specified in the unobtrusive adapter // do your validation here an return true or false }); // you then need to hook the custom validation attribute into the MS unobtrusive validators $.validator.unobtrusive.adapters.add( "booleanrequired", // adapter name ["booleanrequired"], // the names for the properties on the object that will be passed to the validator method function(options) { // set the properties for the validator method options.rules["booleanRequired"] = options.params; // set the message to output if validation fails options.messages["booleanRequired] = options.message; }); } (jQuery)); 

另一种方式(有点像黑客,我不喜欢它)是在模型上有一个始终设置为true的属性,然后使用CompareAttribute来比较* AgreeTerms *属性的值。 很简单,但我不喜欢它:)