Skip to content

Instantly share code, notes, and snippets.

@bestlong
Last active August 29, 2015 14:04
Show Gist options
  • Save bestlong/354d776b8870802a6155 to your computer and use it in GitHub Desktop.
Save bestlong/354d776b8870802a6155 to your computer and use it in GitHub Desktop.
jquery.validator for Taiwan ID
//增加固定長度的 validation rule
$.validator.addMethod("exactlength", function(value, element, param) {
return this.optional(element) || value.length == param;
}, $.validator.format("輸入長度必須為 {0} 個字元."));
$.validator.addMethod("checkTWPID", function(value, element, param) {
var letters = new Array('A', 'B', 'C', 'D',
'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M',
'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V',
'X', 'Y', 'W', 'Z', 'I', 'O');
var multiply = new Array(1, 9, 8, 7, 6, 5, 4, 3, 2, 1);
var nums = new Array(2);
var firstChar;
var firstNumber;
var lastNum;
var totol = 0;
//檢查基本格式
var regExpID =/^[a-z](1|2)\d{8}/i;
if (value.search(regExpID) == -1) {
return false;
}
firstChar = value.charAt(0).toUpperCase();
lastNum = value.charAt(9);
for (var i = 0; i < 26; i++) {
if (firstChar == letters[i]) {
firstNumber = i + 10;
nums[0] = Math.floor(firstNumber / 10);
nums[1] = firstNumber - (nums[0] * 10);
break;
}
}
//加總
for (var i = 0; i < multiply.length; i++) {
if(i<2) {
totol += nums[i] * multiply[i];
} else {
totol += parseInt(value.charAt(i-1)) * multiply[i];
}
}
//比對尾碼
if ((10 - (totol % 10)) != lastNum) {
return false;
}
return true;
}, $.validator.format("身份證格式錯誤."));
$(function (){
$("#form1").validate({
rules: {
name: "required",
ID: {
required: true,
exactlength: 10,
checkTWPID: true
},
relate_name: "required",
relate_ID: {
required: true,
exactlength: 10,
checkTWPID: true
}
},
messages: {
name: {
required: "必須輸入資料"
},
ID: {
required: "必須輸入資料"
},
relate_ID: {
required: "必須輸入資料"
},
relate_name: {
required: "必須輸入資料"
}
}
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment