我已经根据这个问题创建了一个带有 asp.net mvc3 和 jquery validate 的自定义验证属性:
我已将其更新为使用一组字符串属性而不是 bool。哪个工作正常。但是当我将它与自定义 ErrorMessage 一起使用时,我的问题就出现了,自定义消息不显示。我不知道为什么。
[RequiredOneFromGroup("PhoneGroup",
ErrorMessageResourceName = "PhoneGroup",
ErrorMessageResourceType = typeof(WizardStrings))]
public String Mobile { get; set; }
[RequiredOneFromGroup("PhoneGroup",
ErrorMessageResourceName = "PhoneGroup",
ErrorMessageResourceType = typeof(WizardStrings))]
public String Phone { get; set; }
这是自定义验证属性:
[AttributeUsage(AttributeTargets.Property)]
public class RequiredOneFromGroup : ValidationAttribute, IClientValidatable
{
public RequiredOneFromGroup(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 = (string)property.GetValue(validationContext.ObjectInstance, null);
if ( ! string.IsNullOrWhiteSpace(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(string)
let attributes = property.GetCustomAttributes(typeof(RequiredOneFromGroup), false).OfType<RequiredOneFromGroup>()
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;
}
}
我试图删除 ErrorMessage 的手动设置,但我会收到一条空的错误消息。如何检索我在模型的命名参数中指定的 ErrorMessageResourceName 的值?以及如何设置它以便自定义验证属性显示它?