Unity 工具类——身份证验证

字符串存储输入的身份证

校验18位身份证号有效性的方法:

一、身份证规则

18位身份证号的组成:

dddddd yyyy mm dd xx s p 共18位,其中包含:6位地址编码+8位出生日期+3位顺序号+1位校验位

校验方法:

1、前17位数字加权求和,公式:

S=Sum(Ai*Wi),i=0,1,...,16;

Ai:表示第i位身份证号数字,Wi表示第i位的加权因子;

每位权重为: 7  9  10  5  8  4  2  1  6  3  7  9  10  5  8  4  2

 

2、计算对11的模

Y=mod(S,11)

 

3、通过模得到最后一位对应的校验码

Y:0  1  2  3  4  5  6  7  8  9  10

P:1  0  X  9  8  7  6  5  4  3  2

 

二、代码实现

using UnityEngine;

//身份证验证工具类
public class IDCardVertifyUtils : MonoBehaviour
{
    private static bool vertifySuccess = false;

    //权重
    //点击按钮之后验证
    public static bool Verification(string ID)
    {
        vertifySuccess = false;
        if (ID.Length == 18)
        {
            //基本验证位数18位已经通过执行拆分方法
            vertifySuccess = Resolution(ID);
        }

        return vertifySuccess;
    }

    //基本位数验证通过之后开始拆分计算
    private static bool Resolution(string ID)
    {
        int[] numGroup = new int[17];
        int[] weightGroup = new int[] { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 };
        int index = 0;

        int totalNum = 0;
        for (int i = 0; i < numGroup.Length; i++)
        {
            index = i;
            numGroup[index] = int.Parse(ID.Substring(index, 1)) * weightGroup[index];
        }

        for(int i = 0; i < numGroup.Length; i++)
        {
            totalNum += numGroup[i];
        }

        return Judge(totalNum, ID.Substring(17, 1));
    }

    /// <summary>
    /// 计算身份证号码是否合法
    /// </summary>
    /// <param 前17位相加之和="totalNum"></param>
    /// <param 身份证号码最后一位="LastNum"></param>
    private static bool Judge(int totalNum, string LastNum)
    {
        bool result = false;
        int remainder = totalNum % 11;

        if (remainder == 0)
        {
            result = int.Parse(LastNum) == 1;
        }
        else if (remainder == 1)
        {
            result = int.Parse(LastNum) == 0;
        }
        else if (remainder == 2)
        {
            //2对应校验码为X
            result = LastNum == "x" || LastNum == "X";
        }
        else if (remainder >= 3 && remainder <= 10)
        {
            int ln =  int.Parse(LastNum);
            result = remainder + ln == 12;
        }

        return result;
    }
}

 

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值