Skip to content

Instantly share code, notes, and snippets.

@StevenSwann
Created April 11, 2017 13:01
Show Gist options
  • Save StevenSwann/ee4951f6d1d1586f97a4f7e312967f7a to your computer and use it in GitHub Desktop.
Save StevenSwann/ee4951f6d1d1586f97a4f7e312967f7a 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;
}
}
@StevenSwann
Copy link
Author

StevenSwann commented Apr 11, 2017

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.")]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment