我在模型中有以下定义
[Required]
[StringLength(100, MinimumLength = 10)]
[DataType(DataType.Text)]
[Display(Name = "XXX")]
public string XXX{ get; set; }
现在我希望它以不同的方式处理 ACSII 和 Unicode 输入,对于 ASCII,每个字符考虑长度 1,因此需要最小长度 10 和最大长度 50。但是对于 Unicode 字符,我想考虑它的长度 2,所以 5 unicode chars 足以满足最低要求。
我该怎么做?
我想我可能需要两种方法,首先覆盖 asp.net 中的长度检查,然后我需要覆盖 jquery 中的长度检查。不是吗?
这里有人有工作样本吗,谢谢。
最佳答案
为了做你想做的事,你应该能够引入自定义验证属性:
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;
}
}
关于c# - (Asp.Net MVC3) 如何为ASCII 和Unicode 定义StringLength?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8212058/