常用验证逻辑

1,IP

((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)

 

 

2,是否为纯数字


(1)验证字符串中的字符
/// <summary>
/// 用于检查text是否为纯数字
/// </summary>
private bool IsNUM(string text)
{
foreach (char ch in text.ToCharArray())
{
if (ch >= '0' && ch <= '9')
{
continue;
}
else
{
return false;
}
}
return true;
}

 

(2)正则表达式
/// <summary>
/// 验证顺序号是否为非负整数
/// </summary>
/// <param name="seq">顺序号</param>
/// <returns>是否为非负整数</returns>
public static bool RegNum(string seq)
{
if (String.IsNullOrEmpty(seq))
{
return false;
}
Regex reg = new Regex(@"^[1-9]\d*|0$");
return reg.IsMatch(seq);

}

 

 

 

3,数据验证

/// <summary>
/// 验证号码是否重复
/// </summary>
/// <param name="phoneNumber"></param>
/// <returns></returns>
private bool ContainsSameNumbers(string phoneNumber)
{
if (string.IsNullOrEmpty(phoneNumber)) return false;
if (phoneNumber.Contains(','))
{
string[] numbers = phoneNumber.Split(new char[] { ',' });
//冒泡比较
for (int i = 0; i < numbers.Length - 1; i++)
{
for (int j = i + 1; j < numbers.Length; j++)
{
if (numbers[i] == numbers[j])
return true;
}
}
}
return false;
}

/// <summary>
/// 验证日期格式
/// </summary>
/// <param name="date">日期字符串</param>
/// <returns></returns>
private bool RegCheckDate(string date)
{
if (date == null || date == string.Empty)
return true;
string format = @"^((((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-))$";
Regex regDate = new Regex(format);
return regDate.IsMatch(date);
}

//验证电话号码
private bool RegCheckPhoneNum(string num)
{
if (num == null || num == string.Empty)
return true;
Regex regSMS = new Regex(@"^(\d*)$|^((\d+),)+\d+$|^((\d+)/)+\d+$");
return regSMS.IsMatch(num);
}

 

posted @ 2016-05-17 13:34  FiberHomer  阅读(353)  评论(0编辑  收藏  举报