给出以下viewmodel:
public class SomeViewModel
{
public bool IsA { get; set; }
public bool IsB { get; set; }
public bool IsC { get; set; }
//... other properties
}
我希望创建一个自定义属性,该属性验证至少有一个可用属性为true。我设想能够将属性附加到属性并分配如下的组名:
public class SomeViewModel
{
[RequireAtLeastOneOfGroup("Group1")]
public bool IsA { get; set; }
[RequireAtLeastOneOfGroup("Group1")]
public bool IsB { get; set; }
[RequireAtLeastOneOfGroup("Group1")]
public bool IsC { get; set; }
//... other properties
[RequireAtLeastOneOfGroup("Group2")]
public bool IsY { get; set; }
[RequireAtLeastOneOfGroup("Group2")]
public bool IsZ { get; set; }
}
我想在表单提交之前在客户端验证表单更改中的值,这就是为什么我更愿意避免使用类级属性。
这将要求服务器端和客户端验证找到具有相同组名值的所有属性作为自定义属性的参数传入。这可能吗?非常感谢任何指导。
答案 0 :(得分:75)
这是继续下去的一种方式(还有其他方法,我只是说明一个与您的视图模型匹配的方式):
[AttributeUsage(AttributeTargets.Property)]
public class RequireAtLeastOneOfGroupAttribute: ValidationAttribute, IClientValidatable
{
public RequireAtLeastOneOfGroupAttribute(string groupName)
{
ErrorMessage = string.Format("You must select at least one value from group \"{0}\"", groupName);
GroupName = groupName;
}
public string GroupName { get; private set; }
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
foreach (var property in GetGroupProperties(validationContext.ObjectType))
{
var propertyValue = (bool)property.GetValue(validationContext.ObjectInstance, null);
if (propertyValue)
{
// at least one property is true in this group => the model is valid
return null;
}
}
return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
}
private IEnumerable<PropertyInfo> GetGroupProperties(Type type)
{
return
from property in type.GetProperties()
where property.PropertyType == typeof(bool)
let attributes = property.GetCustomAttributes(typeof(RequireAtLeastOneOfGroupAttribute), false).OfType<RequireAtLeastOneOfGroupAttribute>()
where attributes.Count() > 0
from attribute in attributes
where attribute.GroupName == GroupName
select property;
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var groupProperties = GetGroupProperties(metadata.ContainerType).Select(p => p.Name);
var rule = new ModelClientValidationRule
{
ErrorMessage = this.ErrorMessage
};
rule.ValidationType = string.Format("group", GroupName.ToLower());
rule.ValidationParameters["propertynames"] = string.Join(",", groupProperties);
yield return rule;
}
}
现在,让我们定义一个控制器:
public class HomeController : Controller
{
public ActionResult Index()
{
var model = new SomeViewModel();
return View(model);
}
[HttpPost]
public ActionResult Index(SomeViewModel model)
{
return View(model);
}
}
和观点:
@model SomeViewModel
<script src="@Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>
@using (Html.BeginForm())
{
@Html.EditorFor(x => x.IsA)
@Html.ValidationMessageFor(x => x.IsA)
<br/>
@Html.EditorFor(x => x.IsB)<br/>
@Html.EditorFor(x => x.IsC)<br/>
@Html.EditorFor(x => x.IsY)
@Html.ValidationMessageFor(x => x.IsY)
<br/>
@Html.EditorFor(x => x.IsZ)<br/>
<input type="submit" value="OK" />
}
剩下的最后一部分是为客户端验证注册适配器:
jQuery.validator.unobtrusive.adapters.add(
'group',
[ 'propertynames' ],
function (options) {
options.rules['group'] = options.params;
options.messages['group'] = options.message;
}
);
jQuery.validator.addMethod('group', function (value, element, params) {
var properties = params.propertynames.split(',');
var isValid = false;
for (var i = 0; i < properties.length; i++) {
var property = properties[i];
if ($('#' + property).is(':checked')) {
isValid = true;
break;
}
}
return isValid;
}, '');
根据您的具体要求,可能会对代码进行调整。
答案 1 :(得分:4)
require_from_group
:jQuery-validation 项目在 src 文件夹中有一个名为附加的子文件夹。 您可以查看here。
在该文件夹中,我们有许多其他不常见的验证方法,这就是为什么默认情况下不会添加这些方法。
正如您在该文件夹中看到的那样,您需要通过选择实际需要的验证方法来选择许多方法。
根据您的问题,您需要的验证方法在其他文件夹中命名为require_from_group
。
只需下载位于here的相关文件,并将其放入Scripts
应用程序文件夹中。
此方法的文档解释了这一点:
让你说&#34;必须填写至少与选择器Y匹配的X输入。&#34;
最终结果是这些输入都不是:
...将验证,除非其中至少有一个被填充。
partnumber:{require_from_group:[1,&#34; .productinfo&#34;]}, 描述:{require_from_group:[1,&#34; .productinfo&#34;]}
options [0]:必须在组中填充的字段数 options 2:定义条件必需字段组的CSS选择器
此验证方法是通用的,适用于每个input
(文字,复选框,广播等),textarea
和select
。 此方法还允许您指定需要填写的最小所需输入数,例如
partnumber: {require_from_group: [2,".productinfo"]},
category: {require_from_group: [2,".productinfo"]},
description: {require_from_group: [2,".productinfo"]}
我创建了两个类RequireFromGroupAttribute
和RequireFromGroupFieldAttribute
,可以帮助您进行服务器端验证和客户端验证
RequireFromGroupAttribute
类定义 RequireFromGroupAttribute
仅来自Attribute
。该类仅用于配置,例如设置需要为验证填充的字段数。您需要向此类提供验证方法将使用的CSS选择器类,以获取同一组中的所有元素。由于默认的必填字段数为1,因此如果spcefied组中的最低要求大于默认数,则此属性仅用于装饰模型。
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
public class RequireFromGroupAttribute : Attribute
{
public const short DefaultNumber = 1;
public string Selector { get; set; }
public short Number { get; set; }
public RequireFromGroupAttribute(string selector)
{
this.Selector = selector;
this.Number = DefaultNumber;
}
public static short GetNumberOfRequiredFields(Type type, string selector)
{
var requiredFromGroupAttribute = type.GetCustomAttributes<RequireFromGroupAttribute>().SingleOrDefault(a => a.Selector == selector);
return requiredFromGroupAttribute?.Number ?? DefaultNumber;
}
}
RequireFromGroupFieldAttribute
类定义 RequireFromGroupFieldAttribute
派生自ValidationAttribute
并实施IClientValidatable
。您需要在模型中参与组验证的每个属性上使用此类。您必须传递css选择器类。
[AttributeUsage(AttributeTargets.Property)]
public class RequireFromGroupFieldAttribute : ValidationAttribute, IClientValidatable
{
public string Selector { get; }
public bool IncludeOthersFieldName { get; set; }
public RequireFromGroupFieldAttribute(string selector)
: base("Please fill at least {0} of these fields")
{
this.Selector = selector;
this.IncludeOthersFieldName = true;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var properties = this.GetInvolvedProperties(validationContext.ObjectType); ;
var numberOfRequiredFields = RequireFromGroupAttribute.GetNumberOfRequiredFields(validationContext.ObjectType, this.Selector);
var values = new List<object> { value };
var otherPropertiesValues = properties.Where(p => p.Key.Name != validationContext.MemberName)
.Select(p => p.Key.GetValue(validationContext.ObjectInstance));
values.AddRange(otherPropertiesValues);
if (values.Count(s => !string.IsNullOrWhiteSpace(Convert.ToString(s))) >= numberOfRequiredFields)
{
return ValidationResult.Success;
}
return new ValidationResult(this.GetErrorMessage(numberOfRequiredFields, properties.Values), new List<string> { validationContext.MemberName });
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var properties = this.GetInvolvedProperties(metadata.ContainerType);
var numberOfRequiredFields = RequireFromGroupAttribute.GetNumberOfRequiredFields(metadata.ContainerType, this.Selector);
var rule = new ModelClientValidationRule
{
ValidationType = "requirefromgroup",
ErrorMessage = this.GetErrorMessage(numberOfRequiredFields, properties.Values)
};
rule.ValidationParameters.Add("number", numberOfRequiredFields);
rule.ValidationParameters.Add("selector", this.Selector);
yield return rule;
}
private Dictionary<PropertyInfo, string> GetInvolvedProperties(Type type)
{
return type.GetProperties()
.Where(p => p.IsDefined(typeof(RequireFromGroupFieldAttribute)) &&
p.GetCustomAttribute<RequireFromGroupFieldAttribute>().Selector == this.Selector)
.ToDictionary(p => p, p => p.IsDefined(typeof(DisplayAttribute)) ? p.GetCustomAttribute<DisplayAttribute>().Name : p.Name);
}
private string GetErrorMessage(int numberOfRequiredFields, IEnumerable<string> properties)
{
var errorMessage = string.Format(this.ErrorMessageString, numberOfRequiredFields);
if (this.IncludeOthersFieldName)
{
errorMessage += ": " + string.Join(", ", properties);
}
return errorMessage;
}
}
在您的模型中,这里是如何使用它:
public class SomeViewModel
{
internal const string GroupOne = "Group1";
internal const string GroupTwo = "Group2";
[RequireFromGroupField(GroupOne)]
public bool IsA { get; set; }
[RequireFromGroupField(GroupOne)]
public bool IsB { get; set; }
[RequireFromGroupField(GroupOne)]
public bool IsC { get; set; }
//... other properties
[RequireFromGroupField(GroupTwo)]
public bool IsY { get; set; }
[RequireFromGroupField(GroupTwo)]
public bool IsZ { get; set; }
}
默认情况下,您不需要使用RequireFromGroupAttribute
修饰模型,因为默认的必填字段数为1.但如果您希望许多必填字段与1不同,则可以执行以下:
[RequireFromGroup(GroupOne, Number = 2)]
public class SomeViewModel
{
//...
}
@model SomeViewModel
<script src="@Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/require_from_group.js")" type="text/javascript"></script>
@using (Html.BeginForm())
{
@Html.CheckBoxFor(x => x.IsA, new { @class="Group1"})<span>A</span>
@Html.ValidationMessageFor(x => x.IsA)
<br />
@Html.CheckBoxFor(x => x.IsB, new { @class = "Group1" }) <span>B</span><br />
@Html.CheckBoxFor(x => x.IsC, new { @class = "Group1" }) <span>C</span><br />
@Html.CheckBoxFor(x => x.IsY, new { @class = "Group2" }) <span>Y</span>
@Html.ValidationMessageFor(x => x.IsY)
<br />
@Html.CheckBoxFor(x => x.IsZ, new { @class = "Group2" })<span>Z</span><br />
<input type="submit" value="OK" />
}
请注意,在您使用RequireFromGroupField
属性时指定的组选择器将在您的视图中使用,方法是将其指定为组中涉及的每个输入中的类。
这就是服务器端验证的全部内容。
如果您查看GetClientValidationRules
课程中的RequireFromGroupFieldAttribute
实施,您会看到我使用字符串requirefromgroup
而不是require_from_group
作为方法的名称ValidationType
财产。这是因为ASP.Net MVC只允许验证类型的名称包含字母数字字符,并且不能以数字开头。所以你需要添加以下javascript:
$.validator.unobtrusive.adapters.add("requirefromgroup", ["number", "selector"], function (options) {
options.rules["require_from_group"] = [options.params.number, options.params.selector];
options.messages["require_from_group"] = options.message;
});
javascript部分非常简单,因为在adaptater函数的实现中,我们只是将验证委托给正确的require_from_group
方法。
因为它适用于所有类型的input
,textarea
和select
元素,所以我认为这种方式更通用。
希望有所帮助!
答案 2 :(得分:1)
我在我的应用程序中实现了Darin的精彩答案,除了我为字符串而不是布尔值添加它。这是为了名字/公司,电话/电子邮件等。我很喜欢它,除了一个小的挑剔。
我尝试在没有工作电话,手机,家庭电话或电子邮件的情况下提交表单。我在客户端有四个单独的验证错误。这对我来说很好,因为它可以让用户确切地知道可以填写哪些字段以使错误消失。
我输入了一个电子邮件地址。现在,电子邮件下的单一验证消失了,但三者仍在电话号码下。这些也不再是错误了。
因此,我重新分配了jQuery方法,该方法检查验证以解决此问题。代码如下。希望它可以帮到某人。
jQuery.validator.prototype.check = function (element) {
var elements = [];
elements.push(element);
var names;
while (elements.length > 0) {
element = elements.pop();
element = this.validationTargetFor(this.clean(element));
var rules = $(element).rules();
if ((rules.group) && (rules.group.propertynames) && (!names)) {
names = rules.group.propertynames.split(",");
names.splice($.inArray(element.name, names), 1);
var name;
while (name = names.pop()) {
elements.push($("#" + name));
}
}
var dependencyMismatch = false;
var val = this.elementValue(element);
var result;
for (var method in rules) {
var rule = { method: method, parameters: rules[method] };
try {
result = $.validator.methods[method].call(this, val, element, rule.parameters);
// if a method indicates that the field is optional and therefore valid,
// don't mark it as valid when there are no other rules
if (result === "dependency-mismatch") {
dependencyMismatch = true;
continue;
}
dependencyMismatch = false;
if (result === "pending") {
this.toHide = this.toHide.not(this.errorsFor(element));
return;
}
if (!result) {
this.formatAndAdd(element, rule);
return false;
}
} catch (e) {
if (this.settings.debug && window.console) {
console.log("Exception occurred when checking element " + element.id + ", check the '" + rule.method + "' method.", e);
}
throw e;
}
}
if (dependencyMismatch) {
return;
}
if (this.objectLength(rules)) {
this.successList.push(element);
}
}
return true;
};
答案 3 :(得分:0)
我知道这是一个老线程,但我遇到了同样的情况,并找到了一些解决方案,看到一个解决了Matt的问题,所以我想我会分享给那些遇到这个答案的人。查看:MVC3 unobtrusive validation group of inputs