为了做你想做的事,你应该能够引入一个自定义验证属性:
class FooAttribute : ValidationAttribute
{
private readonly int minLength, maxLength;
public FooAttribute(int minLength, int maxLength) : this(minLength, maxLength, "Invalid ASCII/unicode string-length") {}
public FooAttribute(int minLength, int maxLength, string errorMessage) : base(errorMessage)
{
this.minLength = minLength;
this.maxLength = maxLength;
}
protected override ValidationResult IsValid(object value, ValidationContext ctx)
{
if(value == null) return ValidationResult.Success;
var s = value as string;
if(s == null) return new ValidationResult("Not a string");
bool hasNonAscii = s.Any(c => c >= 128);
int effectiveLength = hasNonAscii ? (2*s.Length) : s.Length;
if(effectiveLength < minLength || effectiveLength > maxLength) return new ValidationResult(FormatErrorMessage(ctx.DisplayName));
return ValidationResult.Success;
}
}