public class MyModel { public string Field1 { get; set; }
public string Field2 { get; set; }
}
public class StringLengthComparisonAttribute : ValidationAttribute { private readonly string _dependentProperty; private readonly ComparisonOperator _comparisonOperator; private readonly int _dependentPropertyValue;
public StringLengthComparisonAttribute(string dependentProperty, ComparisonOperator comparisonOperator, int dependentPropertyValue)
{
_dependentProperty = dependentProperty;
_comparisonOperator = comparisonOperator;
_dependentPropertyValue = dependentPropertyValue;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var dependentProperty = validationContext.ObjectType.GetProperty(_dependentProperty);
if (dependentProperty == null)
{
return new ValidationResult($"Unknown property {_dependentProperty}");
}
var dependentPropertyValue = dependentProperty.GetValue(validationContext.ObjectInstance, null);
if (!int.TryParse(dependentPropertyValue.ToString(), out int intDependentPropertyValue))
{
return new ValidationResult($"Property {_dependentProperty} is not of type int");
}
if (value == null)
{
return ValidationResult.Success;
}
var valueString = value.ToString();
var dependentPropertyValueString = dependentPropertyValue.ToString();
if(_comparisonOperator == ComparisonOperator.GreaterThan)
{
if (valueString.Length > intDependentPropertyValue)
{
return new ValidationResult($"The length of {validationContext.DisplayName} must be greater than the length of {_dependentProperty}");
}
}
else if(_comparisonOperator == ComparisonOperator.LessThan)
{
if (valueString.Length < intDependentPropertyValue)
{
return new ValidationResult($"The length of {validationContext.DisplayName} must be less than the length of {_dependentProperty}");
}
}
return ValidationResult.Success;
}
}
在StringComparisonOperator枚举中定义比较运算符。
public enum ComparisonOperator { LessThan, GreaterThan }