校验身份证号、手机号、银行卡号(TypeScript)

16 篇文章 0 订阅
9 篇文章 0 订阅

工具开源仓库https://gitee.com/lililic/information_simulation_open

工具在线地址http://www.onetribe.top/si

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)
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值