.net 中的 [compare(" ")] 数据注释相反?

发布于 2024-12-25 19:38:31 字数 210 浏览 2 评论 0 原文

ASP.NET 中的[Compare(" ")] 数据注释" 的相反/否定是什么?

即:两个属性必须持有不同的值。

public string UserName { get; set; }

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

心如狂蝶 2025-01-01 19:38:32

这是@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-注释/

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/

酷遇一生 2025-01-01 19:38:32

服务器端和客户端验证的完整代码如下:

[AttributeUsage(AttributeTargets.Property)]
public class UnlikeAttribute : ValidationAttribute, IClientModelValidator
{

    private string DependentProperty { get; }

    public UnlikeAttribute(string dependentProperty)
    {
        if (string.IsNullOrEmpty(dependentProperty))
        {
            throw new ArgumentNullException(nameof(dependentProperty));
        }
        DependentProperty = dependentProperty;
    }

    protected override ValidationResult IsValid(object value,
        ValidationContext validationContext)
    {
        if (value != null)
        {
            var otherProperty = validationContext.ObjectInstance.GetType().GetProperty(DependentProperty);
            var otherPropertyValue = otherProperty.GetValue(validationContext.ObjectInstance, null);
            if (value.Equals(otherPropertyValue))
            {
                return new ValidationResult(ErrorMessage);
            }
        }
        return ValidationResult.Success;
    }

    public void AddValidation(ClientModelValidationContext context)
    {
        MergeAttribute(context.Attributes, "data-val", "true");
        MergeAttribute(context.Attributes, "data-val-unlike", ErrorMessage);

        // Added the following code to account for the scenario where the object is deeper in the model's object hierarchy
        var idAttribute = context.Attributes["id"];
        var lastIndex = idAttribute.LastIndexOf('_');
        var prefix = lastIndex > 0 ? idAttribute.Substring(0, lastIndex + 1) : string.Empty;
        MergeAttribute(context.Attributes, "data-val-unlike-property", $"{prefix}{DependentProperty}");
    }

    private void MergeAttribute(IDictionary<string, string> attributes,
        string key,
        string value)
    {
        if (attributes.ContainsKey(key))
        {
            return;
        }
        attributes.Add(key, value);
    }
}

然后在 JavaScript 中包含以下内容:

$.validator.addMethod('unlike',
function (value, element, params) {
    var propertyValue = $(params[0]).val();
    var dependentPropertyValue = $(params[1]).val();
    return propertyValue !== dependentPropertyValue;
});

$.validator.unobtrusive.adapters.add('unlike',
['property'],
function (options) {
    var element = $(options.form).find('#' + options.params['property'])[0];
    options.rules['unlike'] = [element, options.element];
    options.messages['unlike'] = options.message;
});

用法如下:

    public int FromId { get; set; }

    [Unlike(nameof(FromId), ErrorMessage = "From ID and To ID cannot be the same")]
    public int ToId { get; set; }

The complete code for both server side and client side validation is as follows:

[AttributeUsage(AttributeTargets.Property)]
public class UnlikeAttribute : ValidationAttribute, IClientModelValidator
{

    private string DependentProperty { get; }

    public UnlikeAttribute(string dependentProperty)
    {
        if (string.IsNullOrEmpty(dependentProperty))
        {
            throw new ArgumentNullException(nameof(dependentProperty));
        }
        DependentProperty = dependentProperty;
    }

    protected override ValidationResult IsValid(object value,
        ValidationContext validationContext)
    {
        if (value != null)
        {
            var otherProperty = validationContext.ObjectInstance.GetType().GetProperty(DependentProperty);
            var otherPropertyValue = otherProperty.GetValue(validationContext.ObjectInstance, null);
            if (value.Equals(otherPropertyValue))
            {
                return new ValidationResult(ErrorMessage);
            }
        }
        return ValidationResult.Success;
    }

    public void AddValidation(ClientModelValidationContext context)
    {
        MergeAttribute(context.Attributes, "data-val", "true");
        MergeAttribute(context.Attributes, "data-val-unlike", ErrorMessage);

        // Added the following code to account for the scenario where the object is deeper in the model's object hierarchy
        var idAttribute = context.Attributes["id"];
        var lastIndex = idAttribute.LastIndexOf('_');
        var prefix = lastIndex > 0 ? idAttribute.Substring(0, lastIndex + 1) : string.Empty;
        MergeAttribute(context.Attributes, "data-val-unlike-property", 
quot;{prefix}{DependentProperty}");
    }

    private void MergeAttribute(IDictionary<string, string> attributes,
        string key,
        string value)
    {
        if (attributes.ContainsKey(key))
        {
            return;
        }
        attributes.Add(key, value);
    }
}

Then include the following in JavaScript:

$.validator.addMethod('unlike',
function (value, element, params) {
    var propertyValue = $(params[0]).val();
    var dependentPropertyValue = $(params[1]).val();
    return propertyValue !== dependentPropertyValue;
});

$.validator.unobtrusive.adapters.add('unlike',
['property'],
function (options) {
    var element = $(options.form).find('#' + options.params['property'])[0];
    options.rules['unlike'] = [element, options.element];
    options.messages['unlike'] = options.message;
});

Usage is as follows:

    public int FromId { get; set; }

    [Unlike(nameof(FromId), ErrorMessage = "From ID and To ID cannot be the same")]
    public int ToId { get; set; }
幻想少年梦 2025-01-01 19:38:32

在获取/设置逻辑中使用它:

stringA.Equals(stringB) == false

Use this in your get/set logic:

stringA.Equals(stringB) == false

真心难拥有 2025-01-01 19:38:32

除了 @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;
        }

    }

In addition to solution given by @Eitan K, If you want to use other property's display name instead of other property's name, use this snippet:

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

    }
萧瑟寒风 2025-01-01 19:38:31

您可以使用 MVC 万无一失验证中包含的 [NotEqualTo] 数据注释运算符。我现在就用了,效果很好!

MVC Foolproof 是由 @nick-riggs 创建的开源库,具有很多功能可用的验证器。除了进行服务器端验证之外,它还进行客户端非侵入式验证。

开箱即用的内置验证器的完整列表:

包含的操作员验证器

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

包含所需的验证器

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

You can use the [NotEqualTo] data annotation operator included in MVC Foolproof Validation. I used it right now and it works great!

MVC Foolproof is an open source library created by @nick-riggs and has a lot of available validators. Besides doing server side validation it also does client side unobtrusive validation.

Full list of built in validators you get out of the box:

Included Operator Validators

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

Included Required Validators

[RequiredIf]
[RequiredIfNot]
[RequiredIfTrue]
[RequiredIfFalse]
[RequiredIfEmpty]
[RequiredIfNotEmpty]
[RequiredIfRegExMatch]
[RequiredIfNotRegExMatch]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文