123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102 |
- using System;
- namespace YBEE.EQM.Core;
- /// <summary>
- /// 证件号码验证器
- /// </summary>
- public static class CertificateNumberValidator
- {
- /// <summary>
- /// 校验身份证号码
- /// </summary>
- /// <param name="idNumber"></param>
- /// <returns></returns>
- public static IdCardValidateResult ValidateIdCard(string idNumber)
- {
- IdCardValidateResult result = new() { IdNumber = idNumber, Gender = Gender.UNKNOWN, Success = false };
- // 数字验证
- if (idNumber.Length != 18 || long.TryParse(idNumber.Remove(17), out long n) == false || n < Math.Pow(10, 16) || long.TryParse(idNumber.Replace('x', '0').Replace('X', '0'), out _) == false)
- {
- result.ErrorMessage = "格式(应为18位数字,或17位数字+X)";
- return result;
- }
- // 省份验证
- string address = "11x22x35x44x53x12x23x36x45x54x13x31x37x46x61x14x32x41x50x62x15x33x42x51x63x21x34x43x52x64x65x71x81x82x91";
- if (!address.Contains(idNumber.Remove(2), StringComparison.CurrentCulture))
- {
- result.ErrorMessage = "前2位省份代码";
- return result;
- }
- // 出生日期验证
- string birth = idNumber.Substring(6, 8).Insert(6, "-").Insert(4, "-");
- if (DateTime.TryParse(birth, out DateTime birthDate) == false)
- {
- result.ErrorMessage = "第7至14位出生日期";
- return result;
- }
- result.BirthDate = birthDate;
- // 校验码验证
- 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 = idNumber.Remove(17).ToCharArray();
- int sum = 0;
- for (int i = 0; i < 17; i++)
- {
- sum += int.Parse(Wi[i]) * int.Parse(Ai[i].ToString());
- }
- Math.DivRem(sum, 11, out int y);
- if (arrVarifyCode[y] != idNumber.Substring(17, 1).ToLower())
- {
- result.ErrorMessage = "第18位(校验位)";
- return result;
- }
- // 性别
- string g = idNumber.Substring(idNumber.Length - 2, 1);
- if ("02468".Contains(g))
- {
- result.Gender = Gender.FEMALE;
- }
- else
- {
- result.Gender = Gender.MALE;
- }
- result.Success = true;
- //result.ErrorMessage = "符合GB11643-1999标准";
- return result;
- }
- /// <summary>
- /// 身份证号码验证返回结果
- /// </summary>
- public class IdCardValidateResult
- {
- /// <summary>
- /// 身份证号码
- /// </summary>
- public string IdNumber { get; set; }
- /// <summary>
- /// 出生日期
- /// </summary>
- public DateTime? BirthDate { get; set; }
- /// <summary>
- /// 性别
- /// </summary>
- public Gender Gender { get; set; } = Gender.UNKNOWN;
- /// <summary>
- /// 是否成功
- /// </summary>
- public bool Success { get; set; } = false;
- /// <summary>
- /// 错误消息
- /// </summary>
- public string ErrorMessage { get; set; }
- }
- }
|