asp.net 使用数据注解强制模型的布尔值为true

5us2dqdw  于 5个月前  发布在  .NET
关注(0)|答案(5)|浏览(72)

这是一个简单的问题(我认为)。
我有一个表单,表单底部有一个复选框,用户必须同意其中的条款和条件。如果用户没有选中该复选框,我希望在验证摘要中显示一条错误消息,沿着其他表单错误。
我把它添加到我的视图模型中:

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

字符串
但那没用。
有没有一种简单的方法可以通过数据注解强制值为真?

rdrgkggo

rdrgkggo1#

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

字符串

hzbexzde

hzbexzde2#

实际上有一种方法可以让它与DataAnnotations一起工作。下面的方法:

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

字符串

irlmq6kh

irlmq6kh3#

你可以写一个已经提到的自定义验证属性。如果你在做客户端验证,你需要写自定义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来比较你的CompareTerms属性的值。简单的是,但我不喜欢它:)

lxkprmvk

lxkprmvk4#

ASP.NET Core 3.1
我知道这是一个很老的问题,但对于asp.net核心,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;
});

ar7v8xwq

ar7v8xwq5#

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

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

字符串

相关问题