【问题标题】:Enforcing a model's boolean value to be true using data annotations使用数据注释强制模型的布尔值为真
【发布时间】:2011-08-08 18:40:54
【问题描述】:

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

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

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

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

但这没有用。

有没有一种简单的方法可以通过数据注释强制一个值为真?

【问题讨论】:

标签: c# asp.net asp.net-mvc asp.net-mvc-3


【解决方案1】:
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<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            //return new ModelClientValidationRule[] { new ModelClientValidationRule() { ValidationType = "booleanrequired", ErrorMessage = this.ErrorMessage } };
            yield return new ModelClientValidationRule() 
            { 
                ValidationType = "booleanrequired", 
                ErrorMessage = this.ErrorMessageString 
            };
        }
    }
}

【讨论】:

    【解决方案2】:

    您可以编写已经提到的自定义验证属性。如果您正在进行客户端验证,您将需要编写自定义 javascript 以启用不显眼的验证功能来获取它。例如如果您使用的是 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 * 属性的值。很简单,是的,但我不喜欢它:)

    【讨论】:

    • 键区分大小写:booleanrequired booleanRequired
    【解决方案3】:

    实际上有一种方法可以使其与 DataAnnotations 一起使用。如下方式:

        [Required]
        [Range(typeof(bool), "true", "true")]
        public bool AcceptTerms { get; set; }
    

    【讨论】:

    • 这对我不起作用,因为客户端验证同时触发了 true 和 false。
    • 效果很好,并指定错误消息以覆盖默认范围消息:[Required, Range(typeof(bool), "true", "true", ErrorMessage = "Accepting terms is required")]
    【解决方案4】:

    ASP.Net Core 3.1

    我知道这是一个非常古老的问题,但对于 asp.net 核心,IClientValidatable 不存在,我想要一个适用于jQuery Unobtrusive Validation 以及服务器验证的解决方案,所以借助这个 SO 问题@ 987654321@ 我做了一个小修改,适用于复选框等布尔字段。

    属性代码

       [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
        public class MustBeTrueAttribute : ValidationAttribute, IClientModelValidator
        {
            public void AddValidation(ClientModelValidationContext context)
            {
                MergeAttribute(context.Attributes, "data-val", "true");
                var errorMsg = FormatErrorMessage(context.ModelMetadata.GetDisplayName());
                MergeAttribute(context.Attributes, "data-val-mustbetrue", errorMsg);
            }
    
            public override bool IsValid(object value)
            {
                return value != null && (bool)value == true;
            }
    
            private bool MergeAttribute(
                      IDictionary<string, string> attributes,
                      string key,
                      string value)
            {
                if (attributes.ContainsKey(key))
                {
                    return false;
                }
                attributes.Add(key, value);
                return true;
            }
    
        }
    

    型号

        [Display(Name = "Privacy policy")]
        [MustBeTrue(ErrorMessage = "Please accept our privacy policy!")]
        public bool PrivacyPolicy { get; set; }
    

    客户端代码

    $.validator.addMethod("mustbetrue",
        function (value, element, parameters) {
            return element.checked;
        });
    
    $.validator.unobtrusive.adapters.add("mustbetrue", [], function (options) {
        options.rules.mustbetrue = {};
        options.messages["mustbetrue"] = options.message;
    });
    

    【讨论】:

      猜你喜欢
      • 2015-12-17
      • 2016-06-20
      • 2018-11-24
      • 1970-01-01
      • 1970-01-01
      • 2022-12-09
      • 2022-01-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多