gpt4 book ai didi

c# - 两个属性 asp.net mvc 之间条件的数据验证属性

转载 作者:太空狗 更新时间:2023-10-29 17:30:52 26 4
gpt4 key购买 nike

我想在两个属性之间设置一个规则,即一个属性必须大于另一个。那么可以让我这样做的数据验证属性是什么?

这是我的属性

  public int Min{get;set;}
public int Max{get;set;}

如您所见,Max 必须大于 Min。

感谢您的帮助!

最佳答案

我觉得对您的对象进行数据验证是一件好事(以及使用客户端验证)。

这是一个您可以用来执行您所要求的操作的属性(它将能够比较实现 IComparable 的类型对)

public class GreaterThanAttribute : ValidationAttribute
{

public GreaterThanAttribute(string otherProperty)
: base("{0} must be greater than {1}")
{
OtherProperty = otherProperty;
}

public string OtherProperty { get; set; }

public string FormatErrorMessage(string name, string otherName)
{
return string.Format(ErrorMessageString, name, otherName);
}

protected override ValidationResult
IsValid(object firstValue, ValidationContext validationContext)
{
var firstComparable = firstValue as IComparable;
var secondComparable = GetSecondComparable(validationContext);

if (firstComparable != null && secondComparable != null)
{
if (firstComparable.CompareTo(secondComparable) < 1)
{
object obj = validationContext.ObjectInstance;
var thing = obj.GetType().GetProperty(OtherProperty);
var displayName = (DisplayAttribute)Attribute.GetCustomAttribute(thing, typeof(DisplayAttribute));

return new ValidationResult(
FormatErrorMessage(validationContext.DisplayName, displayName.GetName()));
}
}

return ValidationResult.Success;
}

protected IComparable GetSecondComparable(
ValidationContext validationContext)
{
var propertyInfo = validationContext
.ObjectType
.GetProperty(OtherProperty);
if (propertyInfo != null)
{
var secondValue = propertyInfo.GetValue(
validationContext.ObjectInstance, null);
return secondValue as IComparable;
}
return null;
}
}

然后您可以装饰您的模型:

  public int Min{get;set;}

[GreaterThan("Min")]
public int Max{get;set;}

这是一个关于小于验证的有用问题 MVC custom validation: compare two dates但适用于日期而不是整数,但同样的方法适用

关于c# - 两个属性 asp.net mvc 之间条件的数据验证属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25682238/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com