Skip to content

Instantly share code, notes, and snippets.

@LSTANCZYK
Forked from StevenSwann/NotEqualTo
Created September 25, 2017 01:32
Show Gist options
  • Save LSTANCZYK/2edea8527f4ffdc4958219148fef99d1 to your computer and use it in GitHub Desktop.
Save LSTANCZYK/2edea8527f4ffdc4958219148fef99d1 to your computer and use it in GitHub Desktop.
Data Annotation Custom Validation
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public sealed class NotEqualToAttribute : ValidationAttribute
{
private const string DefaultErrorMessage = "{0} cannot be the same as {1}.";
public string OtherProperty { get; private set; }
public NotEqualToAttribute(string otherProperty)
: base(DefaultErrorMessage)
{
if (string.IsNullOrEmpty(otherProperty))
{
throw new ArgumentNullException("otherProperty");
}
OtherProperty = otherProperty;
}
public override string FormatErrorMessage(string name)
{
return string.Format(ErrorMessageString, name, OtherProperty);
}
protected override ValidationResult IsValid(object value,
ValidationContext validationContext)
{
if (value != null)
{
var otherProperty = validationContext.ObjectInstance.GetType()
.GetProperty(OtherProperty);
var otherPropertyValue = otherProperty
.GetValue(validationContext.ObjectInstance, null);
if (value.Equals(otherPropertyValue))
{
return new ValidationResult(
FormatErrorMessage(validationContext.DisplayName));
}
}
return ValidationResult.Success;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment