asp.net-mvc MVC 模型需要 true

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4730183/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 00:45:46  来源:igfitidea点击:

MVC Model require true

asp.net-mvcdata-annotations

提问by Marty Trenouth

Is there a way through data annotations to require that a boolean property be set to true?

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

public class MyAwesomeObj{
    public bool ThisMustBeTrue{get;set;}
}

采纳答案by moribvndvs

You could create your own validator:

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

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
}

回答by dazbradbury

I would create a validator for both Server AND Client side. Using MVC and unobtrusive form validation, this can be achieved simply by doing the following:

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

Firstly, create a class in your project to perform the server side validation like so:

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

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

Following this, annotate the appropriate property in your model:

在此之后,在您的模型中注释适当的属性:

[EnforceTrue(ErrorMessage=@"Error Message")]
public bool ThisMustBeTrue{ get; set; }

And Finally, enable client side validation by adding the following script to your View:

最后,通过将以下脚本添加到您的视图来启用客户端验证:

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

Note: We already created a method GetClientValidationRuleswhich pushes our annotation to the view from our model.

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

If using resource files to supply the error message for internationalization, remove the FormatErrorMessagecall (or just call the base) and tweak the GetClientValidationRulesmethod like so:

如果使用资源文件为国际化提供错误消息,请删除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"
    };
}

回答by fields.cage

I know this is an older post but wanted to share a simple server side way to do this. You create a public property set to true and compare your bool to that property. If your bool is not checked (by default false) the form will not validate.

我知道这是一篇较旧的帖子,但想分享一个简单的服务器端方法来做到这一点。您创建一个公共属性设置为 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; }

Razor code

剃刀代码

@Html.CheckBoxFor(m => Model.AgreeTerms, new { id = "AgreeTerms", @checked = "checked" })
<label asp-for="AgreeTerms" class="control-label"></label>
<a target="_blank" href="/Terms">Read</a>
<br />
@Html.ValidationMessageFor(model => model.AgreeTerms, "", new { @class = "text-danger" })
@Html.HiddenFor(x => Model.isTrue)

回答by Kapé

I tried several solutions but none of them worked completely for me to get both client and server side validation. So what I did in my MVC 5 application to get it to work:

我尝试了几种解决方案,但没有一个完全适合我来获得客户端和服务器端验证。所以我在我的 MVC 5 应用程序中做了什么来让它工作:

In your ViewModel (for server side validation):

在您的 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; }

In your Razor page (for client side validation):

在您的 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>

回答by Harvey

I would just like to direct people to the following Fiddle: https://dotnetfiddle.net/JbPh0X

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

The user added [Range(typeof(bool), "true", "true", ErrorMessage = "You gotta tick the box!")]to their boolean property which causes server side validation to work.

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

In order to also have the client side validation working, they added the following script:

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

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

回答by ta.speot.is

Just check to see whether its string representation is equal to True:

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

[RegularExpression("True")]
public bool TermsAndConditions { get; set; }

回答by Sergey Kudriavtsev

[Required]attribute stands for requiring anyvalue - it can be either true or false. You'd have to use another validation for that.

[Required]属性代表要求任何值 - 它可以是真或假。您必须为此使用另一个验证。

回答by Matthew Manela

You could either create your own attribute or use the CustomValidationAttribute.

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

This is how you would use the CustomValidationAttribute:

这是您将如何使用 CustomValidationAttribute:

[CustomValidation(typeof(BoolValidation), "ValidateBool")]

where BoolValidation is defined as:

其中 BoolValidation 定义为:

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

回答by lobotommy

Following up on the post by ta.speot.is and the comment from Jerad Rose:

跟进 ta.speot.is 的帖子和 Jerad Rose 的评论:

The given post will not work client-side with unobtrusive validation. This should work in both camps (client & server):

给定的帖子将无法通过不显眼的验证在客户端工作。这应该适用于两个阵营(客户端和服务器):

[RegularExpression("(True|true)")]
public bool TermsAndConditions { get; set; }

回答by George Stocker

Do you have the appropriate items set up in the web.config?

您是否在 web.config 中设置了适当的项目

That could cause the validation not to work.

这可能会导致验证不起作用。

You can also try to create a custom validation attribute (since [Required]only cares whether or not it exists, and you care about the value):

您也可以尝试创建自定义验证属性(因为[Required]只关心它是否存在,而您关心的是值):

[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
sealed public class RequiredTrueAttribute : ValidationAttribute
{
    // Internal field to hold the mask value.
    readonly bool accepted;

    public bool Accepted
    {
        get { return accepted; }
    }

    public RequiredTrueAttribute(bool accepted)
    {
        this.accepted = accepted;
    }

    public override bool IsValid(object value)
    {
        bool isAccepted = (bool)value;
        return (isAccepted == true);
    }

    public override string FormatErrorMessage(string name)
    {
        return String.Format(CultureInfo.CurrentCulture,
          ErrorMessageString, name, this.Accepted);
    }
}

Then, usage:

然后,用法:

[RequiredTrue(ErrorMessage="{0} requires acceptance to continue.")]
public bool Agreement {get; set;}

From here.

这里开始