[英]ASP.NET MVC Custom validation for a List<string>
我正在使用ASP.NET MVC 5,并且在客户端要使用JQuery非侵入式验证。
以下是我的模型:
public class CompanyModel
{
public CompanyModel()
{
Employees = new List<EmployeeModel>();
}
public int CompanyId{ get; set; }
public List<EmployeeModel> Employees { get; set; }
}
public class EmployeeModel
{
public EmployeeModel()
{
Values = new List<string>();
}
public string Id { get; set; }
public string Name { get; set; }
[RequiredIf("IsRequired", true, "Atleast one value is required")]
public List<string> Values { get; set; }
public bool IsRequired { get; set; }
}
我能够在服务器端成功实现RequiredIf定制属性。 但是我正在努力进行客户端验证...
在视图中,我遍历雇员列表,并且值集合已绑定
@for (var index = 0; index < Model.Employees.Count; index++)
{
/// some other code
@for (int i = 0; i < Model.employees[index].Values.Count; i++)
{
@Html.TextBoxFor(m => m.Employees[index].Values[i], new {@autocomplete = "false" })
}
}
IsRequired属性是一个隐藏字段:
@Html.HiddenFor(m => m.Employees[index].IsRequired)
以下是我到目前为止用于GetClientValidationRules方法的代码。
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var rule = new ModelClientValidationRule
{
ErrorMessage = ErrorMessage,
ValidationType = "requiredif"
};
rule.ValidationParameters["dependentproperty"] = (context as ViewContext).ViewData.TemplateInfo.GetFullHtmlFieldId(DependentProperty);
rule.ValidationParameters["dependentpropertyvalue"] = DependentPropertyValue.ToString().ToLower();
yield return rule;
}
我没有看到将验证html(data-val- *)属性添加到HTML标记中的值。 而且我也不希望他们如此,因为我认为我缺少一些东西。 如何在html中获取由data-val-requiredif属性填充的value集合的所有元素。
有任何想法吗?
仅供参考:html中的dependentpropertyId的填充方式类似于Employee [0]的CompanyModel.Employees_0_IsRequired。
在验证属性中包含GetClientValidationRules()
方法几乎没有意义,因为它的目的是将data-val-*
属性添加到为该属性生成的表单控件中,并且您不会为属性Values
生成输入如果您这样做,绑定将失败)。 解决此问题的一种方法是处理表格.submit()
事件,检查集合中至少一项是否具有值,如果没有,则取消提交并显示错误。
修改视图以包括验证消息占位符,并在输入中添加类名称以供选择
@for (var index = 0; index < Model.Employees.Count; index++)
{
....
<div class="value-group"> // necessary for relative selectors
@for (int i = 0; i < Model.employees[index].Values.Count; i++)
{
@Html.TextBoxFor(m => m.Employees[index].Values[i], new { @class="value", autocomplete = "false" })
}
@Html.ValidationMessageFor(m => m.Employees[index].Values)
</div>
}
并包含以下脚本
$('form').submit(function() { // use an id selector if you have added one to the form
var isValid = true;
var groups = $('.value-group');
$.each(groups, function(index, item) {
var group = $(this);
var inputs = group.find('.value');
if (inputs.filter(function () { return $(this).val().length > 0; }).length == 0) {
isValid = false;
group.find('span:last').append($('<span></span>').text('At least one value is required')).addClass('field-validation-error').removeClass('field-validation-valid');
}
});
return isValid;
});
如果组中的任何输入现在都有一个值,则您可能还想添加另一个脚本来处理每个输入的change事件,以删除关联的错误消息。
Required
验证仅确保该属性具有值。 对于类似List<string>
,仅意味着它不为null。 空列表仍然是列表,因此可以通过验证。 实际上,您使用的是RequiredIf
,并且没有提供该自定义属性的实现,但是我认为它依赖于基本的Required
属性,因为我所看到的几乎所有实现都可以。
总而言之,您要么需要修改RequiredIf
实现,以考虑列表和其他可枚举属性的内容,要么需要添加一些手动验证来检查列表中是否至少包含一项。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.