前端 JavaScript 驗證**可被繞過** (停用 JS、修改 DOM、直接 POST)。伺服端驗證是**最後防線**,確保資料完整性與安全性。
using System.Text.RegularExpressions;
public bool ValidateFileName(string fileName)
{
// 範例:S_6位數字_6位數字.zip
var pattern = @"^S_\d{6}_\d{6}\.zip$";
return Regex.IsMatch(fileName, pattern);
}
// 使用
if (ValidateFileName("S_123456_200701.zip"))
Console.WriteLine("OK");
else
Console.WriteLine("格式錯誤");
伺服端同步檢查:`Page.IsValid` (在 `btnSubmit_Click` 中判斷)。
| 名稱 | 模式 | 說明 |
|---|---|---|
^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$ | 基本格式,嚴格 RFC 5322 極複雜 | |
| 手機 (台) | ^09\d{8}$ | 09 開頭 10 碼 |
| 身分證 (台) | ^[A-Z][12]\d{8}$ | 字母+性別碼+8碼數字 |
| 身分證 (陸) | ^\d{17}[\dXx]$ | 18 碼,含檢核碼 |
| URL | ^https?://([\w-]+\.)+[\w-]+(/[\w-./?%&=]*)?$ | http/https |
| IPv4 | ^((25[0-5]|2[0-4]\d|[01]?\d?\d)\.){3}(25[0-5]|2[0-4]\d|[01]?\d?\d)$ | 0.0.0.0~255.255.255.255 |
| 中文 | ^[\u4e00-\u9fa5]+$ | 純中文字元 |
| 密碼強度 | ^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$ | 大小寫+數字+特殊符號 8碼以上 |
public static class RegexPatterns
{
// 靜態唯讀 + RegexOptions.Compiled:啟動時編譯為 IL,後續匹配極快
public static readonly Regex Email = new Regex(
@"^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$",
RegexOptions.Compiled | RegexOptions.IgnoreCase);
public static readonly Regex PhoneTw = new Regex(
@"^09\d{8}$",
RegexOptions.Compiled);
}
// 使用
if (RegexPatterns.Email.IsMatch(input)) { ... }
注意:`Compiled` 增加啟動時間與記憶體,**僅用於高頻重用模式**。一次性模式直接 `Regex.IsMatch(input, pattern)` 即可。
// 危險模式:巢狀量詞 + 回溯
// "(a+)+" 匹配 "aaaaaaaaaaaaaaaaX" 會指數級回溯,導致 CPU 100%
var evil = new Regex("(a+)+");
evil.IsMatch("aaaaaaaaaaaaaaaaaaaaaaaaX"); // 卡死
防禦:
(?>...)` 或**佔有量詞** `*+ `++ (需支援)。伺服端正則驗證是資料品質的關鍵閘門。掌握 `Regex.IsMatch`、`RegularExpressionValidator`、預編譯快取、ReDoS 防禦四大支柱,並建立專案共用 `RegexPatterns` 靜態類別,即能兼顧**安全、效能、維護性**。