using System.Text.RegularExpressions;
#region 驗證文本框輸入為數(shù)字 /// <summary> /// 驗證是不是數(shù)字(包含整數(shù)和小數(shù)) /// </summary> /// <param name="str"></param> /// <returns></returns> public static bool GetNum(string str) { return Regex.IsMatch(str,@"^[-]?\d+[.]?\d*$"); } #endregion
#region 驗證文本框輸入為整數(shù) /// <summary> /// 驗證文本框輸入為整數(shù) /// </summary> /// <param name="strNum">輸入字符</param> /// <returns>返回一個bool類型的值</returns> public static bool validateNum(string strNum) { return Regex.IsMatch(strNum, "^[0-9]*$"); } #endregion
#region 驗證文本框輸入為日期 /// <summary> /// 判斷日期 /// </summary> /// <param name="Date"></param> /// <returns></returns> public static bool IsValidDate(string Date) { //驗證YYYY-MM-DD格式,基本上把閏年和2月等的情況都考慮進去 bool bValid = Regex.IsMatch(Date, @"^((((1[6-9]|[2-9]\d)\d{2})-(0?[13578]|1[02])-(0?[1-9]|[12]\d|3[01]))|(((1[6-9]|[2-9]\d)\d{2})-(0?[13456789]|1[012])-(0?[1-9]|[12]\d|30))|(((1[6-9]|[2-9]\d)\d{2})-0?2-(0?[1-9]|1\d|2[0-8]))|(((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))-0?2-29-))$"); return (bValid && Date.CompareTo("1753-01-01") >= 0);
//將平年和閏年的日期驗證表達式合并,我們得到最終的驗證日期格式為YYYY-MM-DD的正則表達式為:
//(([0-9]{3}[1-9]|[0-9]{2}[1-9][0-9]{1}| //[0-9]{1}[1-9][0-9]{2}|[1-9][0-9]{3})-(((0[13578]|1[02])- //(0[1-9]|[12][0-9]|3[01]))|((0[469]|11)-(0[1-9]|[12][0-9]|30))| //(02-(0[1-9]|[1][0-9]|2[0-8]))))|((([0-9]{2})(0[48]|[2468][048]| //[13579][26])|((0[48]|[2468][048]|[3579][26])00))-02-29)
} #endregion
#region 驗證文本框輸入為電子郵件 //驗證電子郵件 public static bool IsValidEmail(string strIn) { return Regex.IsMatch(strIn, @"^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$"); } #endregion
#region 驗證文本框輸入為電話號碼 /// <summary> /// 驗證文本框輸入為電話號碼 /// </summary> /// <param name="strPhone">輸入字符串</param> /// <returns>返回一個bool類型的值</returns> public static bool validatePhone(string strPhone) { return Regex.IsMatch(strPhone, @"\d{3,4}-\d{7,8}"); } #endregion
#region 驗證文本框輸入為傳真號碼 /// <summary> /// 驗證文本框輸入為傳真號碼 /// </summary> /// <param name="strFax">輸入字符串</param> /// <returns>返回一個bool類型的值</returns> public static bool validateFax(string strFax) { return Regex.IsMatch(strFax, @"86-\d{2,3}-\d{7,8}"); } #endregion
獲取IP的字符串 :HttpContext.Current.Request.UserHostAddress
/// <summary>
/// 是否為ip
/// </summary>
/// <param name="ip"></param>
/// <returns></returns>
public static bool IsIP(string ip)
{
return Regex.IsMatch(HttpContext.Current.Request.UserHostAddress, @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$");
}
public static bool IsIPSect(string ip)
{
return Regex.IsMatch(HttpContext.Current.Request.UserHostAddress, @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){2}((2[0-4]\d|25[0-5]|[01]?\d\d?|\*) \.)(2[0-4]\d|25[0-5]|[01]?\d\d?|\*)$");
}
/// <summary>
/// 判斷字符串是否是yy-mm-dd字符串
/// </summary>
/// <param name="str">待判斷字符串</param>
/// <returns>判斷結(jié)果</returns>
public static bool IsDateString(string str)
{
return Regex.IsMatch(str, @"(\d{4})-(\d{1,2})-(\d{1,2})");
}
|