uses
Windows, SysUtils, Classes, Controls, Dialogs, Forms, Math;
const
W_POWER: array[1..18] of byte = (1,2,4,8,5,10,9,7,3,6,1,2,4,8,5,10,9,7);
function isIdentityValid(sCIN: string):Boolean;
var
sBirthDay: string;
i: byte;
wY, wM, wD: word;
dtBirth: TDate;
dtBirth1: TDate;
iSum: cardinal;
begin
Result := True;
//验证 sCIN 长度
if not (length(sCIN) in [15,18]) then
begin
Result := False;
ShowMessage('请输入新代18位身份证号码!');
Exit;
end;
if Length(sCIN) = 15 then
begin
//验证 sCIN 15位是否全为数字
for i := 1 to 15 do
begin
if not (sCIN[i] in ['0'..'9']) then
begin
Result := False;
ShowMessage('第'+IntToStr(i)+'位字符验证不通过,请输入正确的身份证号码!');
Exit;
end;
end;
//验证 sCIN 第7位 ~ 第12位 是否为正确的日期
sBirthDay := copy(sCIN,7,6);
sBirthDay := '19' + sBirthDay;
try
wY := StrToInt(Copy(sBirthDay,1,4));
wM := StrToInt(Copy(sBirthDay,5,2));
wD := StrToInt(Copy(sBirthDay,7,2));
dtBirth := EncodeDate(wY,wM,wD);
dtBirth1 := EncodeDate((wY-60),wM,wD);
if dtBirth < dtBirth1 then
begin
Result := False;
ShowMessage('出生日期验证不通过,年龄超限,请输入正确的身份证号码!');
Exit;
end;
if dtBirth > Date then
begin
Result := False;
ShowMessage('出生日期验证不通过,年龄为负,请输入正确的身份证号码!');
Exit;
end;
except
Result := False;
ShowMessage('出生日期验证不通过,日期无效,请输入正确的身份证号码!');
Exit;
end;
end;
if Length(sCIN) = 18 then
begin
//验证 sCIN 前17位是否全为数字
for i := 1 to 17 do
begin
if not (sCIN[i] in ['0'..'9']) then
begin
Result := False;
ShowMessage('第'+IntToStr(i)+'位字符验证不通过,请输入正确的身份证号码!');
Exit;
end;
end;
//验证 sCIN 第18位只能为数字或者大小写 X
if not (sCIN[18] in ['0'..'9','x','X']) then
begin
Result := False;
ShowMessage('末尾字符验证不通过,请输入正确的身份证号码!');
Exit;
end;
//验证 sCIN 第1位 ~ 第6位 是否为正确的地址码
//验证 sCIN 第7位 ~ 第14位 是否为正确的日期
sBirthDay := copy(sCIN,7,8);
try
wY := StrToInt(Copy(sBirthDay,1,4));
wM := StrToInt(Copy(sBirthDay,5,2));
wD := StrToInt(Copy(sBirthDay,7,2));
dtBirth := EncodeDate(wY,wM,wD);
dtBirth1 := EncodeDate((wY-60),wM,wD);
if dtBirth < dtBirth1 then
begin
Result := False;
ShowMessage('出生日期验证不通过,年龄超限,请输入正确的身份证号码!');
Exit;
end;
if dtBirth > Date then
begin
Result := False;
ShowMessage('出生日期验证不通过,年龄为负,请输入正确的身份证号码!');
Exit;
end;
except
Result := False;
ShowMessage('出生日期验证不通过,日期无效,请输入正确的身份证号码!');
Exit;
end;
//验证 sCIN 末尾是否为正确验证码
iSum := 0;
for i := 1 to 17 do
begin
iSum := iSum + W_POWER[19 - i] * StrToInt(sCIN[i]);
end;
if sCIN[18] in ['x','X'] then iSum := iSum + 10
else iSum := iSum + W_POWER[1] * StrToInt(sCIN[i]);
Result := ((iSum mod 11) = 1);
if not Result then
begin
ShowMessage('末尾验证码验证不通过,请输入正确的身份证号码!');
Exit;
end;
end;
end;
delphi身份证验证函数
最新推荐文章于 2017-08-01 10:53:18 发布