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

Ste*_*ven 20 c# asp.net asp.net-mvc asp.net-mvc-3

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

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

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

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

但那没用.

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

Rya*_*oss 26

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 
            };
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


Rub*_*kér 11

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

    [Required]
    [Range(typeof(bool), "true", "true")]
    public bool AcceptTerms { get; set; }
Run Code Online (Sandbox Code Playgroud)


小智 6

您可以编写已经提到的自定义验证属性.如果您正在进行客户端验证,则需要编写自定义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));
Run Code Online (Sandbox Code Playgroud)

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