【.NET】 增加字符串长度范围校验Attribute

        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属性可供设置最小字符串长度。

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

不死鸟.亚历山大.狼崽子

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值