Атрибут
public class CompareValidatorAttribute : ValidationAttribute, IInstanceValidationAttribute
{
public CompareValidatorAttribute(string prefix, string propertyName) {
Check.CheckNullArgument("propertyName", propertyName);
this.propertyName = propertyName;
this.prefix = prefix;
}
string propertyName, prefix;
public string PropertyName
{
get { return propertyName; }
}
public string Prefix
{
get { return prefix; }
}
#region IInstanceValidationAttribute Members
public bool IsValid(object instance, object value)
{
var property = instance.GetType().GetProperty(propertyName);
var targetValue = property.GetValue(instance, null);
if ((targetValue == null && value == null) || (targetValue != null && targetValue.Equals(value)))
return true;
return false;
}
#endregion
public override bool IsValid(object value)
{
throw new NotImplementedException();
}
}
Интерфейс
public interface IInstanceValidationAttribute
{
bool IsValid(object instance, object value);
}
Валидатор
public class CompareValidator : DataAnnotationsModelValidator<CompareValidatorAttribute>
{
public CompareValidator(ModelMetadata metadata, ControllerContext context, CompareValidatorAttribute attribute)
: base(metadata, context, attribute)
{
}
public override IEnumerable<ModelValidationResult> Validate(object container)
{
if (!(Attribute as IInstanceValidationAttribute).IsValid(container, Metadata.Model))
yield return (new ModelValidationResult
{
MemberName = Metadata.PropertyName,
Message = Attribute.ErrorMessage
});
}
public override IEnumerable<ModelClientValidationRule> GetClientValidationRules()
{
var rule = new ModelClientValidationRule() { ErrorMessage = Attribute.ErrorMessage, ValidationType = "equalTo" };
rule.ValidationParameters.Add("equalTo", "#" + (!string.IsNullOrEmpty(Attribute.Prefix) ? Attribute.Prefix + "_" : string.Empty)+ Attribute.PropertyName);
return new[] { rule };
}
}
Зарегистрируйте его:
DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(CompareValidatorAttribute), typeof(CompareValidator));