2

我在模型中有以下定义

        [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 字符就足够了为最低要求。

我该怎么做?

我想我可能需要两种方法,首先覆盖asp.net中的长度检查,然后我需要覆盖jquery中的长度检查。不是吗?

这里有没有人有工作样本,谢谢。

4

1 回答 1

0

为了做你想做的事,你应该能够引入一个自定义验证属性:

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;
    }
}
于 2011-11-22T06:43:31.730 回答