【问题标题】:(Asp.Net MVC3) How to Define StringLength for ASCII and Unicode?(Asp.Net MVC3) 如何为 ASCII 和 Unicode 定义 StringLength?
【发布时间】:2012-01-02 23:11:44
【问题描述】:

我在模型中有以下定义

        [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 中的长度检查。不是吗?

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

【问题讨论】:

  • .NET 中的字符数据始终为 UTF-16。说到编码长度,我们还需要问……"abc"是ASCII字符串吗?还是一个unicode字符串?它既是(也不是!)。您确定不能在某处编写自定义规则来检查 UTF-8 编码长度吗? (然后“是这个还是那个”的问题没有实际意义,因为 UTF-8 可以同时满足单字节和多字节的情况;不过,它是一种不同的编码)。换句话说:你在这里称什么字符为“unicode”?只有那些 >= 128?
  • 我认为如何使用 System.Globalization.UnicodeCategory 测试一个字符串是 ascii 字符串还是 unicode 字符串很容易
  • unicode 类别不会告诉您与 ASCII 有任何关系。 ASCII 的唯一测试是:它是否 both ASCII unicode。
  • 解释一下 - 这里是按类别分类的 ASCII 字符:pastie.org/2899860
  • 谢谢,但我认为我们在这里忽略了重点。我想要的只是将 abc...长度视为 1 个字符,对于像中文字符这样的 unicode 为 2 个字符,如何处理?对于简单的字符串长度函数,它们之间没有区别

标签: c# unicode ascii string-length


【解决方案1】:

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

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;
    }
}

【讨论】:

  • 谢谢,会试试的。我还需要自己编写 jquery.validation 吗?或者这里有一些捷径
  • @Eric 可能......虽然你可以让那个在服务器端处理?
  • 也许不是。因为Jquery会认为字符串太短,永远不会提交数据:)
猜你喜欢
  • 2012-07-02
  • 1970-01-01
  • 1970-01-01
  • 2011-12-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-02
  • 1970-01-01
相关资源
最近更新 更多