ylbtech-Code-Validator:验证电话号码(可以是固定电话号码或手机号码) |
1、
using System;
using System.Text.RegularExpressions;
namespace Sp.Common
{
public class ValidatorHelper
{
/// <summary>
/// 验证电话号码(可以是固定电话号码或手机号码)
/// [固定电话:[3位或4位区号;区号可以用小括号括起来;区号可以省略;区号与本地号间可以用减号或空格隔开;可以有3位数的分机号,分机号前要加减号]]
/// [手机号码:[可匹配"(+86)013325656352",括号可以省略,+号可以省略,(+86)可以省略,手机号前的0可以省略;手机号第二位数可以是3、4、5、8中的任意一个]]
/// </summary>
/// <param name="input">待验证的字符串</param>
/// <returns>是否匹配</returns>
public static bool IsPhoneNumber(string input)
{
string pattern = @"^((\+)?86|((\+)?86)?)0?1[3458]\d{9}$|^(((0\d{2}|0\d{2})[- ]?)?\d{8}|((0\d{3}|0\d{3})[- ]?)?\d{7})(-\d{3})?$";
return IsMatch(input, pattern);
}
#region 匹配方法
/// <summary>
/// 验证字符串是否匹配正则表达式描述的规则
/// </summary>
/// <param name="inputStr">待验证的字符串</param>
/// <param name="patternStr">正则表达式字符串</param>
/// <returns>是否匹配</returns>
public static bool IsMatch(string inputStr, string patternStr)
{
return IsMatch(inputStr, patternStr, false, false);
}
/// <summary>
/// 验证字符串是否匹配正则表达式描述的规则
/// </summary>
/// <param name="inputStr">待验证的字符串</param>
/// <param name="patternStr">正则表达式字符串</param>
/// <param name="ifIgnoreCase">匹配时是否不区分大小写</param>
/// <returns>是否匹配</returns>
public static bool IsMatch(string inputStr, string patternStr, bool ifIgnoreCase)
{
return IsMatch(inputStr, patternStr, ifIgnoreCase, false);
}
/// <summary>
/// 验证字符串是否匹配正则表达式描述的规则
/// </summary>
/// <param name="inputStr">待验证的字符串</param>
/// <param name="patternStr">正则表达式字符串</param>
/// <param name="ifValidateWhiteSpace">是否验证空白字符串</param>
/// <returns>是否匹配</returns>
public static bool IsMatch1(string inputStr, string patternStr, bool ifValidateWhiteSpace)
{
return IsMatch(inputStr, patternStr, false, ifValidateWhiteSpace);
}
/// <summary>
/// 验证字符串是否匹配正则表达式描述的规则
/// </summary>
/// <param name="inputStr">待验证的字符串</param>
/// <param name="patternStr">正则表达式字符串</param>
/// <param name="ifIgnoreCase">匹配时是否不区分大小写</param>
/// <param name="ifValidateWhiteSpace">是否验证空白字符串</param>
/// <returns>是否匹配</returns>
public static bool IsMatch(string inputStr, string patternStr, bool ifIgnoreCase, bool ifValidateWhiteSpace)
{
if (!ifValidateWhiteSpace && string.IsNullOrEmpty(inputStr))
return false;//如果不要求验证空白字符串而此时传入的待验证字符串为空白字符串,则不匹配
Regex regex = null;
if (ifIgnoreCase)
regex = new Regex(patternStr, RegexOptions.IgnoreCase);//指定不区分大小写的匹配
else
regex = new Regex(patternStr);
return regex.IsMatch(inputStr);
}
#endregion
}
}
2、
原文地址:https://www.cnblogs.com/storebook/p/12685482.html
时间: 2024-10-09 03:01:21