身份证 验证

private bool CheckIDCard_CHS(string IDCard)
{
    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(',');
    string[] Checker = ("1,9,8,7,6,5,4,3,2,1,1").Split(',');
    int intLength = IDCard.Length;

    int i = 0, TotalmulAiWi = 0;
    int modValue = 0;
    string strVerifyCode = "";
    string Ai = "";
    string BirthDay = "";
    int intYear = 0;
    int intMonth = 0;
    int intDay = 0;

    if (intLength == 18)
    {
        Ai = IDCard.Substring(0, 17);
    }
    else if (intLength == 15)
    {
        Ai = IDCard;
        Ai = Ai.Substring(0, 6) + "19" + Ai.Substring(6, 9);
    }
    if (!IsNumeric(Ai)) return false;

    intYear = Convert.ToInt32(Ai.Substring(6, 4));
    intMonth = Convert.ToInt32(Ai.Substring(10, 2));
    intDay = Convert.ToInt32(Ai.Substring(12, 2));

    BirthDay = intYear.ToString() + "-" + intMonth.ToString() + "-" + intDay.ToString();
    if (IsDateTime(BirthDay))
    {
        DateTime DateBirthDay = DateTime.Parse(BirthDay);
        if (DateBirthDay > DateTime.Now)
        {
            return false;
        }

        int intYearLength = DateBirthDay.Year - DateBirthDay.Year;
        if (intYearLength < -140)
        {
            return false;
        }
    }

    if (intMonth > 12 || intDay > 31)
    {
        return false;
    }

    for (i = 0; i < 17; i++)
    {
        TotalmulAiWi = TotalmulAiWi + (Convert.ToInt32(Ai.Substring(i, 1)) * Convert.ToInt32(Wi[i].ToString()));
    }
    modValue = TotalmulAiWi % 11;

    strVerifyCode = arrVarifyCode[modValue].ToString();
    Ai = Ai + strVerifyCode;
    if (intLength == 18 && IDCard != Ai)
    {
        return false;
    }
    return true;
}
/// 判断字符串是否可转换为DateTime
/// 要判断的字符串
/// true=可以转换;false=无法转换
private bool IsDateTime(string s)
{
    try
    {
        System.DateTime.Parse(s);
    }
    catch
    {
        return false;
    }
    return true;
}

/// 判断字符串是否可以转换为数字
///
/// 要判断的字符串
/// true=可以转换;false=无法转换
private bool IsNumeric(object value)
{
    try
    {
        double i = Convert.ToDouble(value.ToString());
        return true;
    }
    catch (FormatException)
    {
        return false;
    }
}

你可能感兴趣的:(身份证)