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

问题描述 投票:0回答:6

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

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

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

[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
6个回答
28
投票
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 
            };
        }
    }
}

12
投票

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

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

7
投票

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


3
投票

ASP.Net Core 3.1

我知道这是一个非常古老的问题,但对于 asp.net core

IClientValidatable
不存在,我想要一个可以与
jQuery Unobtrusive Validation
以及服务器验证一起使用的解决方案,所以在这个 SO 问题 Link 的帮助下我做了一个小修改,可以使用布尔字段(例如复选框)。

属性代码

   [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;
});

2
投票

从.NET 8开始,您可以像这样使用数据注释属性“AllowedValues”:

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

0
投票

如果您希望此属性应该出现在正文或请求负载中,您可以使用它

JsonProperty("yourPropertyname", Required = Required.Always)]
public bool yourPropertyname{ get; set; }
© www.soinside.com 2019 - 2024. All rights reserved.