-
-
Save LSTANCZYK/2edea8527f4ffdc4958219148fef99d1 to your computer and use it in GitHub Desktop.
Data Annotation Custom Validation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[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