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屬性可供設定最小字串長度。