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つのユニコード文字で十分です。最小限の要件のため。

どうすればいいのですか?

私は2つのアプローチが必要かもしれないと思います。最初に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 に答える