验证字符串格式 :
/// <summary>
/// 检查账号格式(字母和数字)
/// </summary>
/// <param name="account">字符串</param>
/// <param name="minL">最小长度</param>
/// <param name="maxL">最大长度</param>
/// <param name="type">验证类型</param>
/// <returns></returns>
private ResultModel CheckStringFormat(string account, int minL, int maxL, int? type)
{
ResultModel result = new ResultModel();
string pattern = "";
// 默认为 字母或数字
type = type == null ? 2 : type;
switch (type) {
case 1:
//所有字符必须为数字
pattern = @"^[0-9]*$";
break;
case 2:
//所有字符必须为字母或数字
pattern = @"^[a-zA-Z0-9]*$";
break;
case 3:
//所有字符小写字母或数字
pattern = @"^[a-z0-9]*$";
break;
case 4:
//以大写字母开头,后面的都是数字
pattern = @"^[A-Z][0-9]*$";
break;
case 5:
//匹配 333-22 格式,三个数字加-加两个数字
pattern = @"^\d{3}-\d{2}$";
break;
default:
break;
}
if (minL<0|| maxL<0)
{
return new ResultModel { Code = -3, Msg = "参数非法,长度必须大于0" };
}
if (minL> maxL)
{
int tempNum = maxL;
maxL = minL;
minL = tempNum;
}
if (account.Length >= minL && account.Length <= maxL) //限制字符串长度再minL和maxL之间
{
if (System.Text.RegularExpressions.Regex.IsMatch(account, pattern))
{
result.Code = 0;
result.Msg = "ok";
}
else
{
result.Code = -1;
result.Msg = "格式不满足要求";
}
}
else
{
result.Code = -1;
result.Msg = "格式不满足要求,长度需在" + minL + "~" + maxL + "之间!";
}
return result;
}
public class ResultModel
{
public int Code { get; set; }
public string Msg { get; set; }
}