Skip to content

Instantly share code, notes, and snippets.

@jchannon
Created April 10, 2012 16:40
Show Gist options
  • Select an option

  • Save jchannon/2352725 to your computer and use it in GitHub Desktop.

Select an option

Save jchannon/2352725 to your computer and use it in GitHub Desktop.
public class MyAdaptor : IDataAnnotationsValidatorAdapter
{
protected readonly ValidationAttribute attribute;
public MyAdaptor(MatchAttribute attribute)
{
this.attribute = attribute;
}
public IEnumerable<ModelValidationRule> GetRules()
{
yield return new MatchValidationRule(attribute.FormatErrorMessage,
new[] { ((MatchAttribute)attribute).SourceProperty },
((MatchAttribute)attribute).SourceProperty,
((MatchAttribute)attribute).MatchProperty);
}
public IEnumerable<ModelValidationError> Validate(object instance)
{
var context =
new ValidationContext(instance, null, null)
{
MemberName = ((MatchAttribute)attribute).SourceProperty
};
var result =
attribute.GetValidationResult(instance, context);
if (result != null)
{
yield return new ModelValidationError(result.MemberNames, attribute.FormatErrorMessage);
}
yield break;
}
}
public class MatchValidationRule : ModelValidationRule
{
public MatchValidationRule(Func<string, string> errorMessageFormatter, IEnumerable<string> memberNames, string SourceProp, string MatchProp)
: base("Match", errorMessageFormatter, memberNames)
{
this.SourceProperty = SourceProp;
this.MatchProperty = MatchProp;
}
public string SourceProperty { get; set; }
public string MatchProperty { get; set; }
}
public class MyFactory : IModelValidatorFactory
{
#region IModelValidatorFactory Members
public IModelValidator Create(Type type)
{
var attributes = type.GetCustomAttributes(typeof(MatchAttribute), false);
MatchAttribute classAttribute = null;
if (attributes.Length > 0)
{
classAttribute = (MatchAttribute)attributes[0];
}
return new MyModelValidator(new MyAdaptor(classAttribute));
}
#endregion
}
public class MyModelValidator : IModelValidator
{
MyAdaptor adaptor;
public MyModelValidator(MyAdaptor adapter)
{
adaptor = adapter;
}
#region IModelValidator Members
public ModelValidationDescriptor Description
{
get
{
return new ModelValidationDescriptor(adaptor.GetRules());
}
}
public ModelValidationResult Validate(object instance)
{
var errors = new List<ModelValidationError>();
errors.AddRange(adaptor.Validate(instance));
return new ModelValidationResult(errors);
}
#endregion
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment