我正在为Visual Studio 2015中的验证开发ASP.NET MVC 5.2.3自定义数据注释。它需要采取任意数量的字段并确保如果有值,他们都必须有价值;如果它们全部为空/空白,则应该没问题。ASP.NET MVC自定义多字段验证
举几个例子帮助:
- ASP.NET MVC implement custom validator use IClientValidatable
- MVC Form Validation on Multiple Fields
- http://www.macaalay.com/2014/02/24/unobtrusive-client-and-server-side-age-validation-in-mvc-using-custom-data-annotations/
但是,我不知道该怎么办,你有一个客户端验证未知数量的字段被验证。
您如何通过IClientValidatable
接口的GetClientValidationRules()
方法的实现将它传递给客户端?
另外,如何将这个新的数据注释应用到我的视图模型的属性?它会是这样吗?
[MultipleRequired("AppNumber", "UserId", /* more fields */), ErrorMessage = "Something..."]
[DisplayName("App #")]
public int AppNumber { get; set; }
[DisplayName("User ID")]
public int UserId { get; set; }
这里的,据我可以与MultipleRequiredAttribute
自定义数据的注释类获得:
public class MultipleRequiredAttribute : ValidationAttribute, IClientValidatable
{
private readonly string[] _fields;
public MultipleRequiredAttribute(params string[] fields)
{
_fields = fields;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
// If any field has value, then all must have value
var anyHasValue = _fields.Any(f => !string.IsNullOrEmpty(f));
if (!anyHasValue) return null;
foreach (var field in _fields)
{
var property = validationContext.ObjectType.GetProperty(field);
if (property == null)
return new ValidationResult($"Property '{field}' is undefined.");
var fieldValue = property.GetValue(validationContext.ObjectInstance, null);
if (string.IsNullOrEmpty(fieldValue?.ToString()))
return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
}
return null;
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
yield return new ModelClientValidationRule
{
ErrorMessage = ErrorMessage,
ValidationType = "multiplerequired"
};
}
}
谢谢。
你建立jQuery验证JS在客户端插件自定义函数 – Steve
首先阅读[ASP.NET MVC 3验证完整指南 - 第二部分](http://www.devtrends.co.uk/blog/the-complete-guide-to-validation-in-asp.net -mvc -3-部分-2)。在你的'GetClientValidationRules()'方法中,你添加一个'ModelClientValidationRule',你可以在其中传递一个逗号分隔的属性名称列表 - 也就是你的'fields'值 - 可以在客户端脚本中解析和使用如果你有问题,请告诉我,我会添加一个答案,但不会有机会几个小时) –
谢谢@StephenMuecke!我的问题之一是如何将价值传递给客户。 – Alex