[Angular] 身分證驗證器(directive Validator)
身分證的產生和驗證是很常見的表單需求
idno-valiator.directive.ts
import { AbstractControl, ValidatorFn } from '@angular/forms';
export function IdnoValiator(): ValidatorFn {
return (control: AbstractControl): { [key: string]: any } | null => {
if (!control.value) {
return null;
}
const valid = checkID(control.value);
return valid ? null : { idnoCheck: true };
};
}
function checkID(id) {
// 建立字母分數陣列(A~Z)
const city = new Array(
1,
10,
19,
28,
37,
46,
55,
64,
39,
73,
82,
2,
11,
20,
48,
29,
38,
47,
56,
65,
74,
83,
21,
3,
12,
30,
);
id = id.toUpperCase();
// 使用「正規表達式」檢驗格式
if (id.search(/^[A-Z](1|2)\d{8}$/i) === -1) {
return false;
} else {
// 將字串分割為陣列(IE必需這麼做才不會出錯)
id = id.split('');
// 計算總分
let total = city[id[0].charCodeAt(0) - 65];
for (let i = 1; i <= 8; i++) {
total += eval(id[i]) * (9 - i);
}
// 補上檢查碼(最後一碼)
total += eval(id[9]);
// 檢查比對碼(餘數應為0);
return total % 10 === 0;
}
}
TS檔
this.formDataService.serviceFormGroup.controls.counterbci
.get('bcI0080')
.setValidators([IdnoValiator()]);
這樣寫法
可以直接從control.value 抓值
所以就不必另外設置變數傳值進來這個驗證器中了
然後有的網站寫的身分證驗證不合格
曾經用身分證字號
M131787720
這個應該是合法身分證
但是卻被驗成不合格
所以歡迎用這身分證做是否符合條件的驗證
參考網站
https://people.debian.org/~paulliu/ROCid.html
https://liaosankai.pixnet.net/blog/post/24165900-%E8%BA%AB%E4%BB%BD%E8%AD%89%E9%A9%97%E8%AD%89%E7%A8%8B%E5%BC%8F-for-javascript-%28%E7%B2%BE%E7%B0%A1%E7%89%88%29
留言
張貼留言