閱讀998 返回首頁    go 阿裏雲 go 技術社區[雲棲]


驗證工具類以及基本驗證方法

 

把下麵的代碼放在一個類中,叫"Utility.cs"

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text.RegularExpressions;
using System.Text;
using System.Web.UI.WebControls;

namespace Tool
{
    public class Utility
    {
        private static Regex RegPhone = new Regex("^[0-9]+[-]?[0-9]+[-]?[0-9]$");
        private static Regex RegNumber = new Regex("^[0-9]+$");
        private static Regex RegNumberSign = new Regex("^[+-]?[0-9]+$");
        private static Regex RegDecimal = new Regex("^[0-9]+[.]?[0-9]+$");
        private static Regex RegDecimalSign = new Regex("^[+-]?[0-9]+[.]?[0-9]+$"); //等價於^[+-]?\d+[.]?\d+$
        private static Regex RegEmail = new Regex("^[\\w-]+@[\\w-]+\\.(com|net|org|edu|mil|tv|biz|info)$");//w 英文字母或數字的字符串,和 [a-zA-Z0-9] 語法一樣
        private static Regex RegCHZN = new Regex("[\u4e00-\u9fa5]");

  
        /// <summary>
        /// 驗證文本數據是不是為空
        /// </summary>
        /// <param name="o">對象</param>
        /// <returns>布爾型</returns>
        public static bool CheckFormTextNotEmpty(object o)
        {
            if (o == null || o.ToString().Trim().Length == 0)
            {
                return false;
            }
            else
            {
                return true;
            }
        }

        /// <summary>
        /// 判斷對象是否為Int32類型的數字
        /// </summary>
        /// <param name="Expression"></param>
        /// <returns></returns>
        public static bool IsNumeric(object Expression)
        {
            if (Expression != null)
            {
                string str = Expression.ToString();
                if (str.Length > 0 && str.Length <= 11 && Regex.IsMatch(str, @"^[-]?[0-9]*[.]?[0-9]*$"))
                {
                    if ((str.Length < 10) || (str.Length == 10 && str[0] == '1') || (str.Length == 11 && str[0] == '-' && str[1] == '1'))
                    {
                        return true;
                    }
                }
            }
            return false;

        }

        /// <summary>
        /// 從Session裏麵獲取UserInfo
        /// </summary>
        /// <returns></returns>
        public static Model.UserInfo GetUserFromSession()
        {
            object o = System.Web.HttpContext.Current.Session["SafeSystemUserInfo"];
            if (o != null)
                return (o as Model.UserInfo);
            else
                return null;
        }

        /// <summary>
        /// 從Session裏麵移除UserInfo
        /// </summary>
        /// <returns></returns>
        public static void RemoveUserFromSession()
        {
           System.Web.HttpContext.Current.Session["SafeSystemUserInfo"]=""; 
        }

 

        /// <summary>
        /// 保存員工信息到Session
        /// </summary>
        /// <param name="staff"></param>
        public static void SavaUserInSession(Model.UserInfo user)
        {
            System.Web.HttpContext.Current.Session["SafeSystemUserInfo"] = user;
        }
       


  #region 數字字符串檢查  
        public static bool IsPhone(string inputData)
        {
            Match m = RegPhone.Match(inputData);
            return m.Success;
        }
  /// <summary>
  /// 檢查Request查詢字符串的鍵值,是否是數字,最大長度限製
  /// </summary>
  /// <param name="req">Request</param>
  /// <param name="inputKey">Request的鍵值</param>
  /// <param name="maxLen">最大長度</param>
  /// <returns>返回Request查詢字符串</returns>
  public static string FetchInputDigit(HttpRequest req, string inputKey, int maxLen)
  {
   string retVal = string.Empty;
   if(inputKey != null && inputKey != string.Empty)
   {
    retVal = req.QueryString[inputKey];
    if(null == retVal)
     retVal = req.Form[inputKey];
    if(null != retVal)
    {
     retVal = SqlText(retVal, maxLen);
     if(!IsNumber(retVal))
      retVal = string.Empty;
    }
   }
   if(retVal == null)
    retVal = string.Empty;
   return retVal;
  }  
  /// <summary>
  /// 是否數字字符串
  /// </summary>
  /// <param name="inputData">輸入字符串</param>
  /// <returns></returns>
  public static bool IsNumber(string inputData)
  {
   Match m = RegNumber.Match(inputData);
   return m.Success;
  }

  /// <summary>
  /// 是否數字字符串 可帶正負號
  /// </summary>
  /// <param name="inputData">輸入字符串</param>
  /// <returns></returns>
  public static bool IsNumberSign(string inputData)
  {
   Match m = RegNumberSign.Match(inputData);
   return m.Success;
  }  
  /// <summary>
  /// 是否是浮點數
  /// </summary>
  /// <param name="inputData">輸入字符串</param>
  /// <returns></returns>
  public static bool IsDecimal(string inputData)
  {
   Match m = RegDecimal.Match(inputData);
   return m.Success;
  }  
  /// <summary>
  /// 是否是浮點數 可帶正負號
  /// </summary>
  /// <param name="inputData">輸入字符串</param>
  /// <returns></returns>
  public static bool IsDecimalSign(string inputData)
  {
   Match m = RegDecimalSign.Match(inputData);
   return m.Success;
  }

        /// <summary>
        ///  驗證輸入大小是否超過了數據庫允許的大小
        /// </summary>
        /// <param name="input">輸入的內容</param>
        /// <param name="maxlength">最大長度</param>
        /// <returns></returns>
        public static bool IsGreaterThanStandardLength(string input, int maxlength)
        {
            if (input.Length >= maxlength)
            {
                return false;
            }
            else
            {
                return true;
            }
        }

  #endregion

  #region 中文檢測

  /// <summary>
  /// 檢測是否有中文字符
  /// </summary>
  /// <param name="inputData"></param>
  /// <returns></returns>
  public static bool IsHasCHZN(string inputData)
  {
   Match m = RegCHZN.Match(inputData);
   return m.Success;
  } 

  #endregion

  #region 郵件地址
  /// <summary>
  /// 是否是浮點數 可帶正負號
  /// </summary>
  /// <param name="inputData">輸入字符串</param>
  /// <returns></returns>
  public static bool IsEmail(string inputData)
  {
   Match m = RegEmail.Match(inputData);
   return m.Success;
  }  

  #endregion

        #region 日期格式判斷
        /// <summary>
        /// 日期格式字符串判斷
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static bool IsDateTime(string str)
        {
            try
            {
                if (!string.IsNullOrEmpty(str))
                {
                    DateTime.Parse(str);
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch
            {
                return false;
            }
        }
        #endregion

        #region 其他

        /// <summary>
  /// 檢查字符串最大長度,返回指定長度的串
  /// </summary>
  /// <param name="sqlInput">輸入字符串</param>
  /// <param name="maxLength">最大長度</param>
  /// <returns></returns>   
  public static string SqlText(string sqlInput, int maxLength)
  {   
   if(sqlInput != null && sqlInput != string.Empty)
   {
    sqlInput = sqlInput.Trim();       
    if(sqlInput.Length > maxLength)//按最大長度截取字符串
     sqlInput = sqlInput.Substring(0, maxLength);
   }
   return sqlInput;
  }  
  /// <summary>
  /// 字符串編碼
  /// </summary>
  /// <param name="inputData"></param>
  /// <returns></returns>
  public static string HtmlEncode(string inputData)
  {
   return HttpUtility.HtmlEncode(inputData);
  }
  /// <summary>
  /// 設置Label顯示Encode的字符串
  /// </summary>
  /// <param name="lbl"></param>
  /// <param name="txtInput"></param>
  public static void SetLabel(Label lbl, string txtInput)
  {
   lbl.Text = HtmlEncode(txtInput);
  }
  public static void SetLabel(Label lbl, object inputObj)
  {
   SetLabel(lbl, inputObj.ToString());
  }  
  //字符串清理
  public static string InputText(string inputString, int maxLength)
  {   
   StringBuilder retVal = new StringBuilder();

   // 檢查是否為空
   if ((inputString != null) && (inputString != String.Empty))
   {
    inputString = inputString.Trim();
    
    //檢查長度
    if (inputString.Length > maxLength)
     inputString = inputString.Substring(0, maxLength);
    
    //替換危險字符
    for (int i = 0; i < inputString.Length; i++)
    {
     switch (inputString[i])
     {
      case '"':
       retVal.Append("&quot;");
       break;
      case '<':
       retVal.Append("&lt;");
       break;
      case '>':
       retVal.Append("&gt;");
       break;
      default:
       retVal.Append(inputString[i]);
       break;
     }
    }    
    retVal.Replace("'", " ");// 替換單引號
   }
   return retVal.ToString();
   
  }
  /// <summary>
  /// 轉換成 HTML code
  /// </summary>
  /// <param name="str">string</param>
  /// <returns>string</returns>
  public static string Encode(string str)
  {   
   str = str.Replace("&","&amp;");
   str = str.Replace("'","''");
   str = str.Replace(""","&quot;");
   str = str.Replace(" ","&nbsp;");
   str = str.Replace("<","&lt;");
   str = str.Replace(">","&gt;");
   str = str.Replace("\n","<br>");
   return str;
  }
  /// <summary>
  ///解析html成 普通文本
  /// </summary>
  /// <param name="str">string</param>
  /// <returns>string</returns>
  public static string Decode(string str)
  {   
   str = str.Replace("<br>","\n");
   str = str.Replace("&gt;",">");
   str = str.Replace("&lt;","<");
   str = str.Replace("&nbsp;"," ");
   str = str.Replace("&quot;",""");
   return str;
  }

        public static string SqlTextClear(string sqlText)
        {
            if (sqlText == null)
            {
                return null;
            }
            if (sqlText == "")
            {
                return "";
            }
            sqlText = sqlText.Replace(",", "");//去除,
            sqlText = sqlText.Replace("<", "");//去除<
            sqlText = sqlText.Replace(">", "");//去除>
            sqlText = sqlText.Replace("--", "");//去除--
            sqlText = sqlText.Replace("'", "");//去除'
            sqlText = sqlText.Replace(""", "");//去除"
            sqlText = sqlText.Replace("=", "");//去除=
            sqlText = sqlText.Replace("%", "");//去除%
            sqlText = sqlText.Replace(" ", "");//去除空格
            return sqlText;
        }
  #endregion

        #region 是否由特定字符組成
        public static bool isContainSameChar(string strInput)
        {
            string charInput = string.Empty;
            if (!string.IsNullOrEmpty(strInput))
            {
                charInput = strInput.Substring(0, 1);
            }
            return isContainSameChar(strInput, charInput, strInput.Length);
        }

        public static bool isContainSameChar(string strInput, string charInput, int lenInput)
        {
            if (string.IsNullOrEmpty(charInput))
            {
                return false;
            }
            else
            {
                Regex RegNumber = new Regex(string.Format("^([{0}])+$", charInput));
                //Regex RegNumber = new Regex(string.Format("^([{0}]{{1}})+$", charInput,lenInput));
                Match m = RegNumber.Match(strInput);
                return m.Success;
            }
        }
        #endregion

        #region 檢查輸入的參數是不是某些定義好的特殊字符:這個方法目前用於密碼輸入的安全檢查
        /// <summary>
        /// 檢查輸入的參數是不是某些定義好的特殊字符:這個方法目前用於密碼輸入的安全檢查
        /// </summary>
        public static bool isContainSpecChar(string strInput)
        {
            string[] list = new string[] { "123456", "654321" };
            bool result = new bool();
            for (int i = 0; i < list.Length; i++)
            {
                if (strInput == list[i])
                {
                    result = true;
                    break;
                }
            }
            return result;
        }
        #endregion
    }
}

 

基本驗證方法

            string strErr = "";
            if (!Utility.IsNumber(YearTxt.Value))
            {
                strErr += "通知卡文號時間錯誤!\\n";
            }
            if (NumberTxt.Value.Trim().Length==0)
            {
                strErr += "文檔編號不能為空!\\n";
            }
            if (ChargeNameTxt.Value.Trim().Length == 0)
            {
                strErr += "部門負責人不能為空!\\n";
            }
            if (!Utility.IsDateTime(CompleteDateTxt.Value))
            {
                strErr += "整改日期格式不正確!\\n";
            }

            if (strErr != "")
            {
                JScript.Alert(strErr);
                return;
            }

            else

            {

            .......................

            }

最後更新:2017-04-02 22:16:08

  上一篇:go php優點和缺點
  下一篇:go tomca的用戶設置