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