txt_idCar_TextChanged(object sender, TextChangedEventArgs e)
{
try
{
//获取页面数据
string strIdCard =
txt_idCar.Text.Trim();
//1.验证身份证准确性
if (strIdCard.Length== 18)
{
//闰年出生日期的合法性正则表达式 || 平年出生日期的合法性正则表达式
if (!Regex.IsMatch(strIdCard, @"(^[1-9][0-9]{5}(19|20)[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9]))[0-9]{3}[0-9Xx]$)") ||
!Regex.IsMatch(strIdCard, @"(^[1-9][0-9]{5}(19|20)[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|1[0-9]|2[0-8]))[0-9]{3}[0-9Xx]$)"))
{
MessageBox.Show("身份证不合法","系统提示",MessageBoxButton.OK,MessageBoxImage.Information);
txt_idCar.Text = null;
}
else
{
//2.切割字符串
string keys = strIdCard;
//性别
int sex = int.Parse(keys.Substring(16,1));
//截取倒数第二位数是偶数表示是女性,奇数表示是男性
//取余
if (sex % 2 == 0)
{
cbo_gender.SelectedValue = 77;//77跟下拉框ID值对应
}
else
{
cbo_gender.SelectedValue = 76;//76跟下拉框ID值对应
}
//年
string birth_y =keys.Substring(6, 4);
//月
string birth_m =keys.Substring(10, 2)
//日
string birth_d =keys.Substring(12, 2);
//拼接出生日期:年+月+日
dtp_Birthday.Text = birth_y + "年" + birth_m + "月" + birth_d + "日";
//获取今年年份
string strNow = DateTime.Now.Year.ToString();
//把今年转化为数字
decimal decNow = Convert.ToDecimal(strNow);
//获取(截取身份证)出生年份
decimal decbirth_y = Convert.ToDecimal(birth_y);
//获取虚岁
decimal decAge = Convert.ToDecimal(decNow -decbirth_y) + 1;
//绑定年龄
txt_Age.Text =decAge.ToString().Trim();
}
}
else if(txt_idCar.Text.ToString().Length == 6)
{
string strAddress = CheckIDCardGetDiQu.LoadAddress(txt_idCar.Text.ToString());
if (strAddress == "")
{
MessageBox.Show("身份证不合法","系统提示",MessageBoxButton.OK,MessageBoxImage.Information);
}
else
{
//绑定联系地址
txt_Address.Text =strAddress;
}
}
}
catch (Exception)
{
throw;
}
}
![在这里插入图片描述](https://img-blog.csdnimg.cn/20190609144226143.PNG)
WPF验证身份证准确性
最新推荐文章于 2020-07-29 16:18:43 发布