Lets say I have a StartDate and an EndDate and I wnt to check if the EndDate is not more then 3 months apart from the Start Date
public class DateCompare : V
The Attribute
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();
}
}
The Interface
public interface IInstanceValidationAttribute
{
bool IsValid(object instance, object value);
}
The Validator
public class CompareValidator : DataAnnotationsModelValidator
{
public CompareValidator(ModelMetadata metadata, ControllerContext context, CompareValidatorAttribute attribute)
: base(metadata, context, attribute)
{
}
public override IEnumerable Validate(object container)
{
if (!(Attribute as IInstanceValidationAttribute).IsValid(container, Metadata.Model))
yield return (new ModelValidationResult
{
MemberName = Metadata.PropertyName,
Message = Attribute.ErrorMessage
});
}
public override IEnumerable 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 };
}
}
Register it:
DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(CompareValidatorAttribute), typeof(CompareValidator));