1、银行卡号校验:
/**
* @desc Luhn算法(直接传入银行卡号即可校验银行卡号,但不校验银行卡号长度)
* @param { string } no
* @param { boolean } computeLast // 是否获取检验总和(通常用来生成校验位)
* */
function luhnCheck<T>(no: string, computeLast:boolean = false): T{
let s: number = 0
if(computeLast) no += '0'
no.split('').reverse().forEach((n: string, index: number) => {
if((index + 1)%2) { // 奇数
s += Number(n)
} else { // 偶数
const nn = Number(n)*2
s = s + (nn < 9 ? nn : (nn - 9))
}
})
return (computeLast ? (10 - s%10)%10 : s%10 === 0 ) as T
}
2、身份证号校验
export default class IdCardNohandle {
/**
* @description 根据身份证号前17位计算出最后一位
* @param { string } n 身份证号前17位
* @returns { string } 最后一位
*/
static computeLastNum(n: string): string {
const computeNums = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]
const remainderToLast = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2']
let total = 0
n.split("").forEach((n, i) => {
total += Number(n) * computeNums[i]
})
return remainderToLast[total%11]
}
/**
* @description 检验身份证号格式是否正确
* @param { string } n 身份证号
* @returns { boolean }
*/
static validateIdNo(n: string): boolean {
// 检验长度
if(n.length !== 18) return false
// 地区是否存在(需要有地区的库,可以查看开源项目)
// if(!Area.validateAreaCodeExist(n.substr(0, 6))) return false
// 校验最后一位
return this.computeLastNum(n.substr(0, 17)) === n.substr(17, 1)
}
}
3、手机号校验
const PHONE_NO = /^(0|86|17951)?(13[0-9]|15[012356789]|16[67]|17[1235678]|18[0-9]|19[01356789]|14[0578])[0-9]{8}$/
/**
* @description 校验手机号格式是否正确
* @param { string } n 手机号
* @returns { boolean }
*/
function validateNo(n: string): boolean {
return PHONE_NO.test(n)
}