ASP.Net MVC探索之路 – 增加字串長度範圍校正Attribute

來源:互聯網
上載者:User
DataAnnotations提供了RequiredAttribute進行null或Empty校正、StringLengthAttribute進行字串長度校正,很奇怪怎麼不提供一個StringLengthRangeAttribute校正。比如我們在校正輸入時,可能要求輸入密碼在6-20這個範圍內,這時候我們自己擴充一個ValidationAttribute就行了,很簡單:[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property
, AllowMultiple = false, Inherited = true)]
public class StringLengthRangeAttribute : ValidationAttribute
{
    private const string _defaultErrorMessage = "'{0}' 長度請保持在 {1}-{2} 個字元之間";

    public StringLengthRangeAttribute(int minLength, int maxLength)
        : base(_defaultErrorMessage)
    {
        if (minLength < 0)
            throw new ArgumentOutOfRangeException("minLength", minLength
                , "字串最小長度不能小於0");
        if (maxLength < 0)
            throw new ArgumentOutOfRangeException("maxLength", maxLength
                , "字串最大長度不能小於0");
        if (maxLength <= minLength)
            throw new ArgumentOutOfRangeException("maxLength", maxLength
                , "字串最大長度必須大於最小長度");
        MinLength = minLength;
        MaxLength = maxLength;
    }

    public override bool IsValid(object value)
    {
        string valueAsString = value as string;
        if (String.IsNullOrEmpty(valueAsString)) return true;
        return valueAsString.Length >= MinLength 
            && valueAsString.Length <= MaxLength;
    }
    public override string FormatErrorMessage(string name)
    {
        return String.Format(CultureInfo.CurrentUICulture, ErrorMessageString,
            name, MinLength, MaxLength);
    }
    public int MaxLength
    {
        get;
        private set;
    }

    public int MinLength
    {
        get;
        private set;
    }
}

使用舉例:

public class UserInputEdit
{
    [StringLengthRange(6, 20, ErrorMessage = "登入密碼請保持在6-20個字元之間")]
    [DisplayName("登入密碼")]
    public string Password { get; private set; }

}

後記:.Net 4下,System.ComponentModel.DataAnnotations命名空間下的StringLengthAttribute增加了MinimumLength屬性可供設定最小字串長度。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.