Подтвердить что ты не робот

Напротив [compare ("")] аннотации данных в .net?

Что противоположность/отрицание аннотации данных [Compare(" ")] "в ASP.NET?

i.e: два свойства должны содержать разные значения.

public string UserName { get; set; }

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

Ответ 1

Вы можете использовать оператор аннотации данных [NotEqualTo], включенный в MVC Foolproof Validation. Я использовал его прямо сейчас, и он отлично работает!

MVC Foolproof - это библиотека с открытым исходным кодом, созданная @nick-riggs и имеющая множество доступных валидаторов. Помимо проверки на стороне сервера, он также выполняет ненавязчивую проверку на стороне клиента.

Полный список встроенных валидаторов вы получаете из коробки:

Включенные валидаторы операторов

[Is]
[EqualTo]
[NotEqualTo]
[GreaterThan]
[LessThan]
[GreaterThanOrEqualTo]
[LessThanOrEqualTo]

Включенные обязательные проверки

[RequiredIf]
[RequiredIfNot]
[RequiredIfTrue]
[RequiredIfFalse]
[RequiredIfEmpty]
[RequiredIfNotEmpty]
[RequiredIfRegExMatch]
[RequiredIfNotRegExMatch]

Примечание. Если вы планируете использовать MVC Foolproof lib и поддерживать локализацию, убедитесь, что примените исправление, которое я здесь представил: https://foolproof.codeplex.com/SourceControl/list/patches

Ответ 2

Это реализация (серверная сторона) ссылки, на которую ссылается @Sverker84.

[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;
    }
}

Применение:

public string UserName { get; set; }

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

Подробности об этой реализации и о том, как ее реализовать на стороне клиента, можно найти здесь:

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/

Ответ 3

Используйте это в логике get/set:

stringA.Equals(stringB) == false

Ответ 4

В дополнение к решению, заданному @Eitan K, Если вы хотите использовать другое отображаемое имя свойства вместо другого имени свойства, используйте этот фрагмент:

[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 OtherPropertyDisplayName { get; private set; }
        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, OtherPropertyDisplayName);
        }

        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))
                {
                    OtherPropertyDisplayName = otherProperty.GetCustomAttribute<DisplayAttribute>().Name;
                    return new ValidationResult(
                        FormatErrorMessage(validationContext.DisplayName));
                }
            }

            return ValidationResult.Success;
        }

    }