using System;
namespace YBEE.EQM.Core;
///
/// 证件号码验证器
///
public static class CertificateNumberValidator
{
///
/// 校验身份证号码
///
///
///
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;
}
///
/// 身份证号码验证返回结果
///
public class IdCardValidateResult
{
///
/// 身份证号码
///
public string IdNumber { get; set; }
///
/// 出生日期
///
public DateTime? BirthDate { get; set; }
///
/// 性别
///
public Gender Gender { get; set; } = Gender.UNKNOWN;
///
/// 是否成功
///
public bool Success { get; set; } = false;
///
/// 错误消息
///
public string ErrorMessage { get; set; }
}
}