您的位置:首页 > 编程语言 > C#

C# 验证/升位公民身份号码/身份证号码 最简单的 本人原创使用请缴纳版权费用!

2010-02-01 22:09 656 查看
谁还有更简单的请留言!部分代码方便调试,未精简。

VerifyIdCard.cs

using System;
using System.Text.RegularExpressions;

namespace Hongcing
{
/// <summary>
/// 验证公民身份号码/身份证号码升位
/// </summary>
public static class VerifyIdCard
{
static readonly int[] iW = { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 };
//static readonly char[] szVerCode ={ '1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2' };
static readonly string szVerCode = "10X98765432";

/// <summary>
/// 获取校验码
/// </summary>
/// <param name="id">17位字符串</param>
/// <returns>返回的校验码</returns>
private static char GetVerifyCode(string id)
{
if (!Regex.IsMatch(id, @"^\d{17}$"))
throw new ArgumentException("必须是17位数字", "id");

int iS = 0;
for (int i = 0, j = 0; i < id.Length && j < iW.Length; i++, j++)
{
int iA = id[i] - '0';
iS += iA * iW[j];
}
int iY = iS % 11;
return szVerCode[iY];
}

/// <summary>
/// 公民身份号码 15 位升级为 18 位
/// </summary>
/// <param name="id">15 位公民身份号码</param>
/// <returns>18 位公民身份号码</returns>
public static string Upgrade(string id)
{
if (!Regex.IsMatch(id, @"^\d{15}$"))
throw new ArgumentException("必须是15位数字", "id");

string tempId = id.Insert(6, "19");
string newId = tempId + GetVerifyCode(tempId);
return newId;
}

/// <summary>
/// 验证 18 位公民身份号码是否有效
/// </summary>
/// <param name="id">18 位公民身份号码</param>
/// <returns>有效为 true,无效为 false</returns>
public static bool Verify(string id)
{
if (!Regex.IsMatch(id, @"^\d{17}[0-9X]$"))
throw new ArgumentException("必须是18位数字或者前17位为数字最后一位为大写字母 X", "id");

string tempId = id.Substring(0, 17);
char oldVerifyCode = id[17];
char newVerifyCode = GetVerifyCode(tempId);
return oldVerifyCode == newVerifyCode;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: