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

Rol*_*sta 14 c# asp.net validation asp.net-mvc data-annotations

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

即:两个属性必须包含不同的值.

public string UserName { get; set; }

[Something["UserName"]]
public string Password { get; set; }
Run Code Online (Sandbox Code Playgroud)

Len*_*rri 8

您可以使用MVC Foolproof Validation中[NotEqualTo]包含的数据注释运算符.我现在用它,效果很好!

MVC Foolproof是一个由@ nick-riggs创建的开源库,有很多可用的验证器.除了进行服务器端验证之外,它还可以进行客户端不显眼的验证.

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

包含的运算符验证器

[Is]
[EqualTo]
[NotEqualTo]
[GreaterThan]
[LessThan]
[GreaterThanOrEqualTo]
[LessThanOrEqualTo]
Run Code Online (Sandbox Code Playgroud)

包含必需的验证者

[RequiredIf]
[RequiredIfNot]
[RequiredIfTrue]
[RequiredIfFalse]
[RequiredIfEmpty]
[RequiredIfNotEmpty]
[RequiredIfRegExMatch]
[RequiredIfNotRegExMatch]
Run Code Online (Sandbox Code Playgroud)

注意:如果您计划使用MVC Foolprooflib并支持本地化,请确保应用我在此处提供的补丁:https://foolproof.codeplex.com/SourceControl/list/patches


Eit*_*n K 7

这是@ 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;
    }
}
Run Code Online (Sandbox Code Playgroud)

用法:

public string UserName { get; set; }

[Unlike("UserName")]
public string AlternateId { get; set; } 
Run Code Online (Sandbox Code Playgroud)

有关此实现的详细信息以及如何在客户端实现它,请访问:

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/


Mat*_*att 7

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

[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);
    }
}
Run Code Online (Sandbox Code Playgroud)

然后在 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;
});
Run Code Online (Sandbox Code Playgroud)

用法如下:

    public int FromId { get; set; }

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