c# - (Asp.Net MVC3) 如何为ASCII 和Unicode 定义StringLength?

标签 c# unicode ascii string-length

我在模型中有以下定义

        [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/

相关文章:

c# - XNA:什么是视口(viewport)?

unicode - 检查 Unicode 中字符组合的算法

Unicode 大小写折叠为大写

bash - 带有 unicode 文件路径的 runco​​mmand (haskell)

windows - 如何使用 FOR 循环分配超过 26 个变量?

java - 将非 ASCII 符号降级为最接近的 7 位 ASCII 等价物(最好是 Java)

c# - 拼写检查器推荐

C# 如何通过反射设置 StructLayoutAttribute.Pack?

java - 在java中将字符转换为ASCII数值

c# - Xamarin.Android SQLite.NET 重复列名称 : ID