【发布时间】:2018-04-05 09:03:24
【问题描述】:
我有一个带有自定义验证器的嵌套模型,用于验证子元素。这种方法非常适合服务器端,但是,我还想添加客户端支持。
这是我的模型:
public class Customer
{
public string Name { get; set; } = "";
[AtLeastOneProperty("HomePhone", "WorkPhone", "CellPhone", ErrorMessage = "At least one phone number is required for Customer")]
public Phone phone { get; set; }
public Customer()
{
phone = new Phone();
}
}
public class Phone
{
public string HomePhone { get; set; } = "";
public string WorkPhone { get; set; } = "";
public string WorkExt { get; set; } = "";
public string CellPhone { get; set; } = "";
}
这是我的验证器:
public class AtLeastOnePropertyAttribute : ValidationAttribute, IClientValidatable
{
private readonly string[] _properties;
public AtLeastOnePropertyAttribute(params string[] properties)
{
_properties = properties;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (_properties == null || _properties.Length < 1)
{
return null;
}
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(value);
List<string> props = new List<string>();
props.Add(properties[0].ToString());
foreach (var property in _properties)
{
validationContext = new ValidationContext(value);
var propertyInfo = validationContext.ObjectType.GetProperty(property);
if (propertyInfo == null)
{
return new ValidationResult(string.Format("unknown property {0}", property));
}
var propertyValue = propertyInfo.GetValue(validationContext.ObjectInstance, null);
if (propertyValue is string && !string.IsNullOrEmpty(propertyValue as string))
{
return null;
}
if (propertyValue != null)
{
return null;
}
}
return new ValidationResult(FormatErrorMessage(validationContext.DisplayName), props);
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var rule = new ModelClientValidationRule
{
ErrorMessage = ErrorMessage,
ValidationType = "atleastonerequired"
};
rule.ValidationParameters["properties"] = string.Join(",", _properties);
yield return rule;
}
}
此代码适用于服务器端验证,但是,我无法让它为我正在检查的那些属性构建客户端验证不显眼的标签。现在它正在尝试为类级别 Phone 构建标签,因为属性标签位于嵌套模型属性而不是单个属性之上。
甚至可以让它添加客户端标签吗?也许制作一个验证适配器?
【问题讨论】:
标签: c# jquery asp.net-mvc validation unobtrusive-validation