C# – Opposite of [compare(” “)] data annotation in .net

asp.netasp.net-mvccdata-annotationsvalidation

What is the opposite/negate of [Compare(" ")] data annotation" in ASP.NET?

i.e: two properties must hold different values.

public string UserName { get; set; }

[Something["UserName"]]
public string Password { get; set; }

Best Answer

This is the implementation (server side) of the link that @Sverker84 referred to.

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public class UnlikeAttribute : ValidationAttribute
{
    private const string DefaultErrorMessage = "The value of {0} cannot be the same as the value of the {1}.";

    public string OtherProperty { get; private set; }

    public UnlikeAttribute(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;
    }
}

Usage:

public string UserName { get; set; }

[Unlike("UserName")]
public string AlternateId { get; set; } 

Details about this implementation, and how to implement it client-side can be found here:

http://www.devtrends.co.uk/blog/the-complete-guide-to-validation-in-asp.net-mvc-3-part-2

http://www.macaalay.com/2014/02/25/unobtrusive-client-and-server-side-not-equal-to-validation-in-mvc-using-custom-data-annotations/