Created
April 11, 2017 13:01
-
-
Save StevenSwann/ee4951f6d1d1586f97a4f7e312967f7a 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
Works exactly the same as the [Compare] tag except it checks if two fields are NOT the same. Useful for checking if a user is trying to set their password to be their username/e-mail.
Example: [NotEqualTo("EmailAddress", ErrorMessage = "The password must not match the e-mail.")]