验证有效身份证
开发工具与关键技术:Visual Studio + XAML
撰写时间:2019年7月12日
在做项目的过程中,很多时候都会涉及一些用户信息,在用户信息中会有一项是验证有效身份证,这验证有效身份证?它应该如何编写代码呢?下面就和你们分享一下我的方法。
1、验证有效身份证,首先要创建一个窗口,这窗口里要写上下面的代码,在浏览器里搞个文本框来填写身份证号码的:(MaxLength:限制输入长度)
<TextBlock Text="身份证号:" Grid.Column="0" Grid.Row="5"/>
<TextBox Grid.Column="1" Grid.Row="5" x:Name="txt_idCar" MaxLength="18" TextChanged="txt_idCar_TextChanged_1"/>
2、在窗口的前台代码中有一个TextChanged的文本改变事件,然后就是在这个文本改变事件里转到定义,来到后台里编写后台代码:
private void txt_idCar_TextChanged_1(object sender, TextChangedEventArgs e)
{
string strIdCard = txt_idCar.Text.Trim();
#region 原来方法
try
{
if (strIdCard.Length == 18) //判断身份证的长度是否等于18
{
//身份证的格式不在这个正则表达式范围内执行
if (!Regex.IsMatch(strIdCard, @"(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)"))
{
MessageBox.Show("身份证不合法!");
txt_idCar.Text = "";
}
else
{
string keys = strIdCard;
//性别
int sex = int.Parse(keys.Substring(16, 1));
//年
string birth_y = keys.Substring(6, 4);
//月
string birth_m = keys.Substring(10, 2);
//日
string birth_d = keys.Substring(12, 2);
ListViewItem l = new ListViewItem();
//绑定出生日期
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();
//取余
if (sex % 2 == 0)
{
cbo_gender.SelectedValue = 77;//77跟下拉框ID值对应
}
else
{
cbo_gender.SelectedValue = 76;//76跟下拉框ID值对应
}
}
}
}
catch
{
MessageBox.Show("输入的身份证不正确。");
}
#endregion
#region 使用高级语法
if (txt_idCar.Text.ToString().Length == 6)
{
string strAddress = CheckIDCardGetDiQu.LoadAddress(txt_idCar.Text.ToString());
if (strAddress == "")
{
MessageBox.Show("身份证不合法!");
}
else
{
txt_Address.Text = strAddress;
}
}
if (txt_idCar.Text.ToString().Length < 6)
{
txt_Address.Text = "";
}
#endregion
}
3、这是界面图: