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;
}
}
, 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; }
}
{
[StringLengthRange(6, 20, ErrorMessage = "登录密码请保持在6-20个字符之间")]
[DisplayName("登录密码")]
public string Password { get; private set; }
}
后记:.Net 4下,System.ComponentModel.DataAnnotations命名空间下的StringLengthAttribute增加了MinimumLength属性可供设置最小字符串长度。