asp.net 中国身份证号码验证代码 非正则
程序员文章站
2024-03-09 16:26:29
复制代码 代码如下: using system; /// /// summary description for idcardvalid /...
复制代码 代码如下:
using system;
/// <summary>
/// summary description for idcardvalid
/// </summary>
public class idcardvalid
{
public idcardvalid()
{
//
// todo: add constructor logic here
//
}
/// <summary>
/// 验证身份证号码
/// </summary>
/// <param name="id">身份证号码</param>
/// <returns>验证成功为true,否则为false</returns>
public static bool checkidcard(string id)
{
if (id.length == 18)
{
bool check = checkidcard18(id);
return check;
}
else if (id.length == 15)
{
bool check = checkidcard15(id);
return check;
}
else
{
return false;
}
}
#region 身份证号码验证
/// <summary>
/// 验证15位身份证号
/// </summary>
/// <param name="id">身份证号</param>
/// <returns>验证成功为true,否则为false</returns>
private static bool checkidcard18(string id)
{
long n = 0;
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)) == -1)
{
return false;//省份验证
}
string birth = id.substring(6, 8).insert(6, "-").insert(4, "-");
datetime time = new datetime();
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 = -1;
math.divrem(sum, 11, out y);
if (arrvarifycode[y] != id.substring(17, 1).tolower())
{
return false;//校验码验证
}
return true;//符合gb11643-1999标准
}
/// <summary>
/// 验证18位身份证号
/// </summary>
/// <param name="id">身份证号</param>
/// <returns>验证成功为true,否则为false</returns>
private static bool checkidcard15(string id)
{
long n = 0;
if (long.tryparse(id, out n) == false || n < math.pow(10, 14))
{
return false;//数字验证
}
string address = "11x22x35x44x53x12x23x36x45x54x13x31x37x46x61x14x32x41x50x62x15x33x42x51x63x21x34x43x52x64x65x71x81x82x91";
if (address.indexof(id.remove(2)) == -1)
{
return false;//省份验证
}
string birth = id.substring(6, 6).insert(4, "-").insert(2, "-");
datetime time = new datetime();
if (datetime.tryparse(birth, out time) == false)
{
return false;//生日验证
}
return true;//符合15位身份证标准
}
#endregion
}
下一篇: asp.net 取消缓存相关问题说明