首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> ASP.NET 基礎 >> 關於ASP.NET

ASP.NET 伺服器端輸入驗證元件庫:通用參數檢驗類

     編輯:關於ASP.NET

設計目標

避免依賴驗證控件產生的大量客戶端腳本,集中實作伺服器端驗證邏輯,涵蓋字串、日期、數字、編碼等常見類型。

ParameterVerify 靜態類核心方法

public static class ParameterVerify
{
    // 1. 非法字元檢查 (防 SQL 注入關鍵字)
    public static bool VerifyString(string strInput)
    {
        if (string.IsNullOrEmpty(strInput)) return true;
        return !Regex.IsMatch(strInput, @"([<>""'])|(delete from)|(drop table)");
    }

    // 2. 日期格式驗證
    public static bool VerifyDate(string strInput)
    {
        if (string.IsNullOrEmpty(strInput)) return false;
        return DateTime.TryParse(strInput, out _);
    }

    // 3. 日期時間格式 (YYYY-MM-DD hh:mm:ss)
    public static bool VerifyDateTime(string strInput)
    {
        if (string.IsNullOrEmpty(strInput)) return false;
        return Regex.IsMatch(strInput, 
            @"^(\d{4})(-|/)?((0[1-9])|(1[0-2]))(-|/)?(((0[1-9])|([1-2][0-9]))|(3[0-1])) ([0-1][0-9])|(2[0-3]):([0-5][0-9]):([0-5][0-9])$");
    }

    // 4. 編碼字串 (字母、數字、-、_)
    public static bool VerifyNo(string strInput, int minSize, int maxSize)
    {
        if (strInput == null) return false;
        string pattern = $@"^((\w)|(_)|(-)|(\s)){{{minSize},{maxSize}}}$";
        return Regex.IsMatch(strInput, pattern);
    }

    // 5. 數字字串 (含小數位數、長度、負號控制)
    public static bool VerifyDecimal(string strInput, int length, int precision, bool allowMinus)
    {
        if (strInput == null) return false;
        string pattern = allowMinus 
            ? $@"^(-?[0-9]{{0,{length-precision}}}\.?|\.[0-9]{{1,{precision}}}|-?[0-9]{{1,{length-precision}}}\.[0-9]{{0,{precision}}})$"
            : $@"^([0-9]{{0,{length-precision}}}\.?|\.[0-9]{{1,{precision}}}|-?[0-9]{{1,{length-precision}}}\.[0-9]{{0,{precision}}})$";
        return Regex.IsMatch(strInput, pattern);
    }

    // 6. 變長字串 (長度+非法字元)
    public static bool VerifyVarchar(string strInput, int minSize, int maxSize)
        => strInput != null && VerifyString(strInput) && strInput.Length >= minSize && strInput.Length <= maxSize;

    // 7. 整數字串
    public static bool VerifyInt(string strInput, bool allowMinus)
    {
        if (strInput == null) return false;
        if (int.TryParse(strInput.Trim(), out int val))
            return allowMinus || val >= 0;
        return false;
    }
}

使用建議

  • 在頁面提交統一入口(如 BasePage)呼叫驗證,失敗時拋出自定義異常或回傳錯誤訊息集合。
  • 正則表達式預編譯靜態唯讀欄位可提升效能。
  • 此為邏輯層驗證,前端仍建議保留基礎客戶端驗證以提升使用者體驗。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved