C# 实施一个模型';使用数据批注将布尔值设置为true
我认为这是一个简单的问题 我有一个表格,底部有一个复选框,用户必须同意条款和条件。如果用户没有选中该框,我希望在验证摘要中显示一条错误消息以及其他表单错误 我将此添加到我的视图模型中:C# 实施一个模型';使用数据批注将布尔值设置为true,c#,asp.net,asp.net-mvc,asp.net-mvc-3,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; } 但那没用 有没有一种简单的方法可以通过数据注释强制值为真?使用Sy
[Required]
[Range(1, 1, ErrorMessage = "You must agree to the Terms and Conditions")]
public bool AgreeTerms { get; set; }
但那没用
有没有一种简单的方法可以通过数据注释强制值为真?使用System.Collections.Generic;
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
};
}
}
}
使用System.ComponentModel.DataAnnotations;
使用System.Threading.Tasks;
使用System.Web.Mvc;
命名空间已检查。实体
{
公共类BooleanRequiredAttribute:ValidationAttribute,IClientValidable
{
公共覆盖布尔值有效(对象值)
{
返回值!=null&(bool)值==true;
}
公共IEnumerable GetClientValidationRules(ModelMetadata元数据、ControllerContext上下文)
{
//返回新的ModelClientValidationRule[]{new ModelClientValidationRule(){ValidationType=“booleanrequired”,ErrorMessage=this.ErrorMessage}};
返回新的ModelClientValidationRule()
{
ValidationType=“booleanrequired”,
ErrorMessage=this.ErrorMessageString
};
}
}
}
您可以编写一个已经提到的自定义验证属性。如果您正在进行客户端验证,则需要编写自定义javascript以启用不引人注目的验证功能。e、 g.如果您正在使用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*属性的值。简单是的,但我不喜欢:)实际上有一种方法可以让它与数据注释一起工作。方法如下:
[Required]
[Range(typeof(bool), "true", "true")]
public bool AcceptTerms { get; set; }
ASP.NETCore3.1
我知道这是一个非常老的问题,但是对于asp.net核心,iclientvalidable
不存在,我想要一个解决方案,可以与jQuery非干扰性验证
以及服务器验证一起使用,因此在这个问题的帮助下,我做了一个小的修改,可以使用类似布尔字段的复选框
属性代码
客户端代码
自定义注释非常容易编写,您考虑过这个选项吗?不适用于bool,但非常类似(并允许自定义错误消息):键区分大小写:booleanrequired booleanrequired这对我不起作用,因为客户端验证同时在true和false上启动。
[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;
});