zoukankan      html  css  js  c++  java
  • ASP.Net MVC探索之路 增加字符串长度范围校验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(
    620, ErrorMessage = "登录密码请保持在6-20个字符之间")]
        [DisplayName(
    "登录密码")]
        
    public string Password { getprivate set; }

    }


    后记:.Net 4下,System.ComponentModel.DataAnnotations命名空间下的StringLengthAttribute增加了MinimumLength属性可供设置最小字符串长度。

  • 相关阅读:
    数据库DQL(Data Query Language)语言学习之一:基础查询
    Mysql查看连接数(连接总数、活跃数、最大并发数)
    完成端口之二:服务器代码
    完成端口之二:线程池部分
    完成端口之一
    日志系统(Log4z源码)
    C++多线程同步之Semaphore(信号量)
    select、poll和epoll的优缺点
    python之切片
    python之Dict和set类型
  • 原文地址:https://www.cnblogs.com/alby/p/stringlengthrangeattribute.html
Copyright © 2011-2022 走看看