一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

javascript验证香港身份证的格式或真实性

时间:2017-03-17 编辑:简简单单 来源:一聚教程网

 代码如下复制代码

functionIsHKID(str) {

 varstrValidChars ="ABCDEFGHIJKLMNOPQRSTUVWXYZ"

 // basic check length

 if(str.length < 8)

 returnfalse;

 // handling bracket

 if(str.charAt(str.length-3) =='('&& str.charAt(str.length-1) ==')')

 str = str.substring(0, str.length - 3) + str.charAt(str.length -2);

 // convert to upper case

 str = str.toUpperCase();

 // regular expression to check pattern and split

 varhkidPat = /^([A-Z]{1,2})([0-9]{6})([A0-9])$/;

 varmatchArray = str.match(hkidPat);

 // not match, return false

 if(matchArray ==null)

 returnfalse;

 // the character part, numeric part and check digit part

 varcharPart = matchArray[1];

 varnumPart = matchArray[2];

 varcheckDigit = matchArray[3];

 // calculate the checksum for character part

 varcheckSum = 0;

 if(charPart.length == 2) {

 checkSum += 9 * (10 + strValidChars.indexOf(charPart.charAt(0)));

 checkSum += 8 * (10 + strValidChars.indexOf(charPart.charAt(1)));

 }else{

 checkSum += 9 * 36;

 checkSum += 8 * (10 + strValidChars.indexOf(charPart));

 }

 // calculate the checksum for numeric part

 for(vari = 0, j = 7; i < numPart.length; i++, j--)

 checkSum += j * numPart.charAt(i);

 // verify the check digit

 varremaining = checkSum % 11;

 varverify = remaining == 0 ? 0 : 11 - remaining;

 returnverify == checkDigit || (verify == 10 && checkDigit =='A');

}

在网上找了很久都没合意的验证方式,最后通过Google找到一个国外写的js验证,发现可以使用。

上面那段验证的很精密,包含身份证真实性的校验,如果只是想验证输入的香港身份证格式,请使用下面的这段js。

 代码如下复制代码

functionIsHKID(str) {

 varstrValidChars ="ABCDEFGHIJKLMNOPQRSTUVWXYZ"

 // basic check length

 if(str.length < 8)

 returnfalse;

 // handling bracket

 if(str.charAt(str.length-3) =='('&& str.charAt(str.length-1) ==')')

 str = str.substring(0, str.length - 3) + str.charAt(str.length -2);

 // convert to upper case

 str = str.toUpperCase();

 // regular expression to check pattern and split

 varhkidPat = /^([A-Z]{1,2})([0-9]{6})([A0-9])$/;

 varmatchArray = str.match(hkidPat);

 // not match, return false

 if(matchArray ==null)

 returnfalse;

 returntrue;

 }

热门栏目