MVC模型要求为真

Mar*_*uth 78 asp.net-mvc data-annotations

有没有办法通过数据注释要求将布尔属性设置为true?

public class MyAwesomeObj{
    public bool ThisMustBeTrue{get;set;}
}
Run Code Online (Sandbox Code Playgroud)

daz*_*ury 129

我会为服务器和客户端创建一个验证器.使用MVC和不显眼的表单验证,只需执行以下操作即可实现:

首先,在项目中创建一个类来执行服务器端验证,如下所示:

public class EnforceTrueAttribute : ValidationAttribute, IClientValidatable
{
    public override bool IsValid(object value)
    {
        if (value == null) return false;
        if (value.GetType() != typeof(bool)) throw new InvalidOperationException("can only be used on boolean properties.");
        return (bool)value == true;
    }

    public override string FormatErrorMessage(string name)
    {
        return "The " + name + " field must be checked in order to continue.";
    }

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        yield return new ModelClientValidationRule
        {
            ErrorMessage = String.IsNullOrEmpty(ErrorMessage) ? FormatErrorMessage(metadata.DisplayName) : ErrorMessage,
            ValidationType = "enforcetrue"
        };
    }
}
Run Code Online (Sandbox Code Playgroud)

在此之后,在模型中注释相应的属性:

[EnforceTrue(ErrorMessage=@"Error Message")]
public bool ThisMustBeTrue{ get; set; }
Run Code Online (Sandbox Code Playgroud)

最后,通过在View中添加以下脚本来启用客户端验证:

<script type="text/javascript">
    jQuery.validator.addMethod("enforcetrue", function (value, element, param) {
        return element.checked;
    });
    jQuery.validator.unobtrusive.adapters.addBool("enforcetrue");
</script>
Run Code Online (Sandbox Code Playgroud)

注意:我们已经创建了一个方法GetClientValidationRules,将我们的注释从我们的模型推送到视图.

如果使用资源文件提供国际化的错误消息,请删除FormatErrorMessage调用(或只调用基数)并调整GetClientValidationRules方法,如下所示:

public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
    string errorMessage = String.Empty;
    if(String.IsNullOrWhiteSpace(ErrorMessage))
    {
        // Check if they supplied an error message resource
        if(ErrorMessageResourceType != null && !String.IsNullOrWhiteSpace(ErrorMessageResourceName))
        {
            var resMan = new ResourceManager(ErrorMessageResourceType.FullName, ErrorMessageResourceType.Assembly);
            errorMessage = resMan.GetString(ErrorMessageResourceName);
        }
    }
    else
    {
        errorMessage = ErrorMessage;
    }

    yield return new ModelClientValidationRule
    {
        ErrorMessage = errorMessage,
        ValidationType = "enforcetrue"
    };
}
Run Code Online (Sandbox Code Playgroud)

  • 谢谢你 - 它很棒!删除重写FormatErrorMessage方法后效果更好 - 这样可以使资源文件中的错误消息本地化工作.我的用法:[EnforceTrue(ErrorMessageResourceType = typeof(ValidationMessages),ErrorMessageResourceName ="TermsAndConditionsRequired")] (3认同)
  • 我无法让客户端验证工作,似乎无法判断我做错了什么。我到底应该把 javacsript 放在哪里?在头部标签?在控制器旁边? (2认同)

小智 84

我知道这是一篇较旧的帖子,但想分享一个简单的服务器端方式来做到这一点.您创建一个设置为true的私有属性,并将您的bool与该属性进行比较.如果未选中您的bool(默认为false),则表单将不会验证.

public bool isTrue
{ get { return true; } }

[Required]
[Display(Name = "I agree to the terms and conditions")]
[Compare("isTrue", ErrorMessage = "Please agree to Terms and Conditions")]
public bool AgreeTerms { get; set; }
Run Code Online (Sandbox Code Playgroud)

  • +1表示简单.仅供参考:我必须公开'isTrue'属性才能使用. (11认同)
  • 如果为"isTrue"属性添加隐藏,则可以获得客户端验证 (9认同)
  • +1在盒子外面思考,简单干净,喜欢它! (3认同)
  • @CutRateGamer,我编辑了将isTrue公之于众的答案. (2认同)
  • 烦人的这个漂亮的解决方案对我不起作用。在 Mvc 5.2.3 上测试。 (2认同)

Hac*_*ese 48

您可以创建自己的验证器:

public class IsTrueAttribute : ValidationAttribute
{
    #region Overrides of ValidationAttribute

    /// <summary>
    /// Determines whether the specified value of the object is valid. 
    /// </summary>
    /// <returns>
    /// true if the specified value is valid; otherwise, false. 
    /// </returns>
    /// <param name="value">The value of the specified validation object on which the <see cref="T:System.ComponentModel.DataAnnotations.ValidationAttribute"/> is declared.
    ///                 </param>
    public override bool IsValid(object value)
    {
        if (value == null) return false;
        if (value.GetType() != typeof(bool)) throw new InvalidOperationException("can only be used on boolean properties.");

        return (bool) value;
    }

    #endregion
}
Run Code Online (Sandbox Code Playgroud)


Kap*_*apé 13

我尝试了几种解决方案,但它们都没有完全为我提供客户端和服务器端验证.那么我在MVC 5应用程序中做了什么让它工作:

在ViewModel中(用于服务器端验证):

public bool IsTrue => true;

[Required]
[Display(Name = "I agree to the terms and conditions")]
[Compare(nameof(IsTrue), ErrorMessage = "Please agree to Terms and Conditions")]
public bool HasAcceptedTermsAndConditions { get; set; }
Run Code Online (Sandbox Code Playgroud)

在Razor页面中(用于客户端验证):

<div class="form-group">
   @Html.CheckBoxFor(m => m.HasAcceptedTermsAndConditions)
   @Html.LabelFor(m => m.HasAcceptedTermsAndConditions)
   @Html.ValidationMessageFor(m => m.HasAcceptedTermsAndConditions)

   @Html.Hidden(nameof(Model.IsTrue), "true")
</div>
Run Code Online (Sandbox Code Playgroud)

  • 注意隐藏字段的值("true")! (3认同)

Har*_*vey 9

我想将人们引导到以下小提琴:https://dotnetfiddle.net/JbPh0X

用户添加 [Range(typeof(bool), "true", "true", ErrorMessage = "You gotta tick the box!")]了他们的布尔属性,这导致服务器端验证工作.

为了使客户端验证工作,他们添加了以下脚本:

// extend jquery range validator to work for required checkboxes
var defaultRangeValidator = $.validator.methods.range;
$.validator.methods.range = function(value, element, param) {
    if(element.type === 'checkbox') {
        // if it's a checkbox return true if it is checked
        return element.checked;
    } else {
        // otherwise run the default validation function
        return defaultRangeValidator.call(this, value, element, param);
    }
}
Run Code Online (Sandbox Code Playgroud)


ta.*_*.is 8

只需检查其字符串表示是否等于True:

[RegularExpression("True")]
public bool TermsAndConditions { get; set; }
Run Code Online (Sandbox Code Playgroud)

  • 确认,这在服务器端有效,但在客户端无效 (2认同)

Ser*_*sev 6

[Required]属性代表需要任何值 - 它可以是true或false.你必须使用另一个验证.


Mat*_*ela 5

您可以创建自己的属性或使用CustomValidationAttribute.

这是您使用CustomValidationAttribute的方式:

[CustomValidation(typeof(BoolValidation), "ValidateBool")]
Run Code Online (Sandbox Code Playgroud)

其中BoolValidation定义为:

public class BoolValidation
{
  public static ValidationResult ValidateBool(bool boolToBeTrue)
  {
    if (boolToBeTrue)
    {
      return ValidationResult.Success;
    }
    else
    {
      return new ValidationResult(
          "Bool must be true.");
    }
  }
Run Code Online (Sandbox Code Playgroud)