与.net中的数据注释相反?
ASP.NET中[Compare(" ")]
数据注释的反面/否定是什么?
即:两个属性必须包含不同的值。
public string UserName { get; set; } [Something["UserName"]] public string Password { get; set; }
您可以使用MVC Foolproof Validation中包含的[NotEqualTo]
数据注释运算符。 我现在用它,效果很好!
MVC Foolproof
是一个由@ nick-riggs创建的开源库,有很多可用的validation器。 除了进行服务器端validation之外,它还可以进行客户端不显眼的validation。
开箱即用的内置validation器的完整列表:
包含的运算符validation器
[Is] [EqualTo] [NotEqualTo] [GreaterThan] [LessThan] [GreaterThanOrEqualTo] [LessThanOrEqualTo]
包含必需的validation者
[RequiredIf] [RequiredIfNot] [RequiredIfTrue] [RequiredIfFalse] [RequiredIfEmpty] [RequiredIfNotEmpty] [RequiredIfRegExMatch] [RequiredIfNotRegExMatch]
注意:如果您打算使用MVC Foolproof
lib并支持本地化 ,请确保应用我在此提供的补丁 : https : //foolproof.codeplex.com/SourceControl/list/patches
这是@ 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; }
有关此实现的详细信息以及如何在客户端实现它,请访问:
https://www.devtrends.co.uk/blog/the-complete-guide-to-validation-in-asp.net-mvc-3-part-2
Unobtrusive Client and Server Side Not Equal To Validation in MVC using Custom Data Annotations
在get / set逻辑中使用它:
stringA.Equals(stringB)== false
除了@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().Name; return new ValidationResult( FormatErrorMessage(validationContext.DisplayName)); } } return ValidationResult.Success; } }
服务器端和客户端validation的完整代码如下:
[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 = ErrorMessage); } } return ValidationResult.Success; } public void AddValidation(ClientModelValidationContext context) { MergeAttribute(context.Attributes, "data-val", "true"); MergeAttribute(context.Attributes, "data-val-unlike", ErrorMessage); MergeAttribute(context.Attributes, "data-val-unlike-property", DependentProperty); } private void MergeAttribute(IDictionary 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; });
用法如下:
上述就是C#学习教程:与.net中的数据注释相反?分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
public int FromId { get; set; } [Unlike(nameof(FromId), ErrorMessage = "From ID and To ID cannot be the same")] public int ToId { get; set; }
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/954174.html