using System;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
namespace CommonTool
{
public sealed class UtilsValid
{
private static readonly Regex RegPhone = new Regex("^[0-9]+[-]?[0-9]+[-]?[0-9]$");
private static readonly Regex RegNumber = new Regex("^[0-9]+$");
private static readonly Regex RegNumberSign = new Regex("^[+-]?[0-9]+$");
private static readonly Regex RegDecimal = new Regex("^[0-9]+[.]?[0-9]+$");
private static readonly Regex RegDecimalSign = new Regex("^[+-]?[0-9]+[.]?[0-9]+$"); //等价于^[+-]?\d+[.]?\d+$
// ReSharper disable once UnusedMember.Local
private static readonly Regex RegEmail = new Regex("^[\\w-]+@[\\w-]+\\.(com|net|org|edu|mil|tv|biz|info)$");//w 英文字母或数字的字符串,和 [a-zA-Z0-9] 语法一样
private static readonly Regex RegChZn = new Regex("[\u4e00-\u9fa5]");
#region 数字字符串检查
public static bool IsPhone(string inputData)
{
Match m = RegPhone.Match(inputData);
return m.Success;
}
///
/// 检查Request查询字符串的键值,是否是数字,最大长度限制
///
/// Request
/// Request的键值
/// 最大长度
/// 返回Request查询字符串
public static string FetchInputDigit(HttpRequest req, string inputKey, int maxLen)
{
string retVal = string.Empty;
if (!string.IsNullOrEmpty(inputKey))
{
retVal = req.QueryString[inputKey] ?? req.Form[inputKey];
if (null != retVal)
{
retVal = SqlText(retVal, maxLen);
if (!IsNumber(retVal))
retVal = string.Empty;
}
}
return retVal ?? (string.Empty);
}
///
/// 是否数字字符串
///
/// 输入字符串
///
public static bool IsNumber(string inputData)
{
Match m = RegNumber.Match(inputData);
return m.Success;
}
///
/// 是否数字字符串 可带正负号
///
/// 输入字符串
///
public static bool IsNumberSign(string inputData)
{
Match m = RegNumberSign.Match(inputData);
return m.Success;
}
///
/// 是否是浮点数
///
/// 输入字符串
///
public static bool IsDecimal(string inputData)
{
Match m = RegDecimal.Match(inputData);
return m.Success;
}
///
/// 是否是浮点数 可带正负号
///
/// 输入字符串
///
public static bool IsDecimalSign(string inputData)
{
Match m = RegDecimalSign.Match(inputData);
return m.Success;
}
#endregion
#region 中文检测
///
/// 检测是否有中文字符
///
///
///
public static bool IsHasChZn(string inputData)
{
Match m = RegChZn.Match(inputData);
return m.Success;
}
#endregion
#region 其他
///
/// 检查字符串最大长度,返回指定长度的串
///
/// 输入字符串
/// 最大长度
///
public static string SqlText(string sqlInput, int maxLength)
{
if (!string.IsNullOrEmpty(sqlInput))
{
sqlInput = sqlInput.Trim();
if (sqlInput.Length > maxLength)//按最大长度截取字符串
sqlInput = sqlInput.Substring(0, maxLength);
}
return sqlInput;
}
///
/// 字符串编码
///
///
///
public static string HtmlEncode(string inputData)
{
return HttpUtility.HtmlEncode(inputData);
}
/////
///// 设置Label显示Encode的字符串
/////
/////
/////
//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 (!string.IsNullOrEmpty(inputString))
{
inputString = inputString.Trim();
//检查长度
if (inputString.Length > maxLength)
inputString = inputString.Substring(0, maxLength);
//替换危险字符
foreach (char str in inputString)
{
switch (str)
{
case '"':
retVal.Append(""");
break;
case '<':
retVal.Append("<");
break;
case '>':
retVal.Append(">");
break;
default:
retVal.Append(str);
break;
}
}
retVal.Replace("'", " ");// 替换单引号
}
return retVal.ToString();
}
///
/// 转换成 HTML code
///
/// string
/// string
public static string Encode(string str)
{
str = str.Replace("&", "&");
str = str.Replace("'", "''");
str = str.Replace("\"", """);
str = str.Replace(" ", " ");
str = str.Replace("<", "<");
str = str.Replace(">", ">");
str = str.Replace("\n", "
");
return str;
}
///
///解析html成 普通文本
///
/// string
/// string
public static string Decode(string str)
{
str = str.Replace("
", "\n");
str = str.Replace(">", ">");
str = str.Replace("<", "<");
str = str.Replace(" ", " ");
str = str.Replace(""", "\"");
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 strInput != null && IsContainSameChar(strInput, charInput, strInput.Length);
}
public static bool IsContainSameChar(string strInput, string charInput, int lenInput)
{
if (string.IsNullOrEmpty(charInput))
{
return false;
}
Regex regNumber = new Regex($"^([{charInput}])+$");
//Regex RegNumber = new Regex(string.Format("^([{0}]{{1}})+$", charInput,lenInput));
Match m = regNumber.Match(strInput);
return m.Success;
}
#endregion
#region 检查输入的参数是不是某些定义好的特殊字符:这个方法目前用于密码输入的安全检查
///
/// 检查输入的参数是不是某些定义好的特殊字符:这个方法目前用于密码输入的安全检查
///
public static bool IsContainSpecChar(string strInput)
{
string[] list = { "123456", "654321" };
bool result = new bool();
foreach (string str in list)
{
if (strInput == str)
{
result = true;
break;
}
}
return result;
}
#endregion
public static bool IsIdCard(string idNum, string birthdayYear, int gender)
{
string input = idNum;
string str2 = "";
string s = "";
int length = input.Length;
if ((length == 15) && (length == 0x12))
{
string pattern = "";
switch (length)
{
case 15:
pattern = "/d{15}";
str2 = "19" + input.Substring(6, 2);
s = input.Substring(14, 1);
break;
case 0x12:
pattern = "/d{17}[0-9x]";
str2 = input.Substring(6, 4);
s = input.Substring(0x10, 1);
break;
}
Regex regex = new Regex(pattern, RegexOptions.Singleline | RegexOptions.IgnoreCase);
if (!regex.Match(input).Success)
{
return false;
}
if ((birthdayYear.Length > 0) && (birthdayYear != str2))
{
return false;
}
if (gender == -1)
{
return true;
}
if ((int.Parse(s) % 2) == 0)
{
if (gender != 0)
{
return false;
}
return false;
}
if (gender != 1)
{
return false;
}
}
return false;
}
#region 验证是不是正常字符 字母,数字,下划线的组合
/**/
///
/// 验证是不是正常字符 字母,数字,下划线的组合
///
///
///
public static bool IsNormalChar(string source)
{
return Regex.IsMatch(source, @"[wd_]+", RegexOptions.IgnoreCase);
}
#endregion
#region 中文
/**/
///
/// 中文
///
///
///
public static bool IsChinese(string source)
{
return Regex.IsMatch(source, @"^[u4e00-u9fa5]+$", RegexOptions.IgnoreCase);
}
public static bool HasChinese(string source)
{
return Regex.IsMatch(source, @"[u4e00-u9fa5]+", RegexOptions.IgnoreCase);
}
#endregion
#region 邮政编码 6个数字
/**/
///
/// 邮政编码 6个数字
///
///
///
public static bool IsPostCode(string source)
{
return Regex.IsMatch(source, @"^d{6}$", RegexOptions.IgnoreCase);
}
#endregion
#region 是不是中国电话,格式010-85849685
/**/
///
/// 是不是中国电话,格式010-85849685
///
///
///
public static bool IsTel(string source)
{
return Regex.IsMatch(source, @"^d{3,4}-?d{6,8}$", RegexOptions.IgnoreCase);
}
#endregion
#region 看字符串的长度是不是在限定数之间 一个中文为两个字符
/**/
///
/// 看字符串的长度是不是在限定数之间 一个中文为两个字符
///
/// 字符串
/// 大于等于
/// 小于等于
///
public static bool IsLengthStr(string source, int begin, int end)
{
int length = Regex.Replace(source, @"[^x00-xff]", "OK").Length;
if ((length <= begin) && (length >= end))
{
return false;
}
return true;
}
#endregion
#region 验证邮箱验证邮箱
/**/
///
/// 验证邮箱
///
///
///
public static bool IsEmail(string source)
{
return Regex.IsMatch(source, @"^[A-Za-z0-9](([_.-]?[a-zA-Z0-9]+)*)@([A-Za-z0-9]+)(([.-]?[a-zA-Z0-9]+)*).([A-Za-z]{2,})$", RegexOptions.IgnoreCase);
}
public static bool HasEmail(string source)
{
return Regex.IsMatch(source, @"[A-Za-z0-9](([_.-]?[a-zA-Z0-9]+)*)@([A-Za-z0-9]+)(([.-]?[a-zA-Z0-9]+)*).([A-Za-z]{2,})", RegexOptions.IgnoreCase);
}
#endregion
#region 验证网址
/**/
///
/// 验证网址
///
///
///
public static bool IsUrl(string source)
{
return Regex.IsMatch(source, @"^(((file|gopher|news|nntp|telnet|http|ftp|https|ftps|sftp)://)|(www.))+(([a-zA-Z0-9._-]+.[a-zA-Z]{2,6})|([0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}))(/[a-zA-Z0-9&%_./-~-]*)?$", RegexOptions.IgnoreCase);
}
public static bool HasUrl(string source)
{
return Regex.IsMatch(source, @"(((file|gopher|news|nntp|telnet|http|ftp|https|ftps|sftp)://)|(www.))+(([a-zA-Z0-9._-]+.[a-zA-Z]{2,6})|([0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}))(/[a-zA-Z0-9&%_./-~-]*)?", RegexOptions.IgnoreCase);
}
#endregion
#region 验证日期
/**/
///
/// 验证日期
///
///
///
public static bool IsDateTime(string source)
{
try
{
// ReSharper disable once UnusedVariable
var time = Convert.ToDateTime(source);
return true;
}
catch
{
return false;
}
}
#endregion
#region 验证手机号
/**/
///
/// 验证手机号
///
///
///
public static bool IsMobile(string source)
{
return Regex.IsMatch(source, @"^1[35]d{9}$", RegexOptions.IgnoreCase);
}
public static bool HasMobile(string source)
{
return Regex.IsMatch(source, @"1[35]d{9}", RegexOptions.IgnoreCase);
}
#endregion
#region 验证IP
/**/
///
/// 验证IP
///
///
///
public static bool IsIp(string source)
{
return Regex.IsMatch(source, @"^(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]).(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0).(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0).(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])$", RegexOptions.IgnoreCase);
}
public static bool HasIp(string source)
{
return Regex.IsMatch(source, @"(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]).(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0).(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0).(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])", RegexOptions.IgnoreCase);
}
#endregion
#region 验证身份证是否有效
/**/
///
/// 验证身份证是否有效
///
///
///
public static bool IsIdCard(string id)
{
if (id.Length == 18)
{
bool check = IsIdCard18(id);
return check;
}
else if (id.Length == 15)
{
bool check = IsIdCard15(id);
return check;
}
else
{
return false;
}
}
public static bool IsIdCard18(string id)
{
long n;
if (long.TryParse(id.Remove(17), out n) == false || n < Math.Pow(10, 16) || long.TryParse(id.Replace('x', '0').Replace('X', '0'), out n) == false)
{
return false;//数字验证
}
string address = "11x22x35x44x53x12x23x36x45x54x13x31x37x46x61x14x32x41x50x62x15x33x42x51x63x21x34x43x52x64x65x71x81x82x91";
if (address.IndexOf(id.Remove(2), StringComparison.Ordinal) == -1)
{
return false;//省份验证
}
string birth = id.Substring(6, 8).Insert(6, "-").Insert(4, "-");
DateTime time;
if (DateTime.TryParse(birth, out time) == false)
{
return false;//生日验证
}
string[] arrVarifyCode = ("1,0,x,9,8,7,6,5,4,3,2").Split(',');
string[] wi = ("7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2").Split(',');
char[] ai = id.Remove(17).ToCharArray();
int sum = 0;
for (int i = 0; i < 17; i++)
{
sum += int.Parse(wi[i]) * int.Parse(ai[i].ToString());
}
int y;
Math.DivRem(sum, 11, out y);
if (arrVarifyCode[y] != id.Substring(17, 1).ToLower())
{
return false;//校验码验证
}
return true;//符合GB11643-1999标准
}
public static bool IsIdCard15(string id)
{
long n;
if (long.TryParse(id, out n) == false || n < Math.Pow(10, 14))
{
return false;//数字验证
}
string address = "11x22x35x44x53x12x23x36x45x54x13x31x37x46x61x14x32x41x50x62x15x33x42x51x63x21x34x43x52x64x65x71x81x82x91";
if (address.IndexOf(id.Remove(2), StringComparison.Ordinal) == -1)
{
return false;//省份验证
}
string birth = id.Substring(6, 6).Insert(4, "-").Insert(2, "-");
DateTime time;
if (DateTime.TryParse(birth, out time) == false)
{
return false;//生日验证
}
return true;//符合15位身份证标准
}
#endregion
#region 是不是Int型的
/**/
///
/// 是不是Int型的
///
///
///
public static bool IsInt(string source)
{
Regex regex = new Regex(@"^(-){0,1}d+$");
if (regex.Match(source).Success)
{
if ((long.Parse(source) > 0x7fffffffL) || (long.Parse(source) < -2147483648L))
{
return false;
}
return true;
}
return false;
}
#endregion
}
}