using System;
using System.Text;
using System.Text.RegularExpressions;
namespace Sp.Common
{
public class ValidatorHelper
{
/// <summary>
/// 验证字符串长度范围
/// [若要验证固定长度,可传入相同的两个长度数值]
/// </summary>
/// <param name="input">待验证的字符串</param>
/// <param name="withEnglishCharacter">是否包含英文字母</param>
/// <param name="withNumber">是否包含数字</param>
/// <param name="withChineseCharacter">是否包含汉字</param>
/// <param name="lengthBegin">长度范围起始值(含)</param>
/// <param name="lengthEnd">长度范围结束值(含)</param>
/// <returns>是否匹配</returns>
public static bool IsStringLengthByInclude(string input, bool withEnglishCharacter, bool withNumber, bool withChineseCharacter, int lengthBegin, int lengthEnd)
{
if (!withEnglishCharacter && !withNumber && !withChineseCharacter)
return false;//如果英文字母、数字和汉字都没有,则返回false
StringBuilder patternString = new StringBuilder();
patternString.Append("^[");
if (withEnglishCharacter)
patternString.Append("a-zA-Z");
if (withNumber)
patternString.Append("0-9");
if (withChineseCharacter)
patternString.Append(@"u4E00-u9FA5");
patternString.Append("]{" + lengthBegin + "," + lengthEnd + "}$");
return IsMatch(input, patternString.ToString());
}
#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
}
}