PRF - Lib - Valida CPF CNPJ

Biblioteca para valida CPF e CNPJ

此腳本不應該直接安裝,它是一個供其他腳本使用的函式庫。欲使用本函式庫,請在腳本 metadata 寫上: // @require https://update.gf.qytechs.cn/scripts/31419/205924/PRF%20-%20Lib%20-%20Valida%20CPF%20CNPJ.js

您需要先安裝使用者腳本管理器擴展,如 TampermonkeyGreasemonkeyViolentmonkey 之後才能安裝該腳本。

You will need to install an extension such as Tampermonkey to install this script.

您需要先安裝使用者腳本管理器擴充功能,如 TampermonkeyViolentmonkey 後才能安裝該腳本。

您需要先安裝使用者腳本管理器擴充功能,如 TampermonkeyUserscripts 後才能安裝該腳本。

你需要先安裝一款使用者腳本管理器擴展,比如 Tampermonkey,才能安裝此腳本

您需要先安裝使用者腳本管理器擴充功能後才能安裝該腳本。

(我已經安裝了使用者腳本管理器,讓我安裝!)

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

(我已經安裝了使用者樣式管理器,讓我安裝!)

// ==UserScript==
// @name         PRF - Lib - Valida CPF CNPJ
// @namespace    br.gov.prf.scripts.lib.validacpfcnpj
// @description  Biblioteca para valida CPF e CNPJ
// @version      1.2
// @author       Marcelo Barros
// @grant        none
// ==/UserScript==

'use strict';

let pesoCPF = [11, 10, 9, 8, 7, 6, 5, 4, 3, 2];
let pesoCNPJ = [6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2];

function calcularDigito(str, peso) {
    let soma = 0;
    for (let indice = str.length - 1, digito; indice >= 0; indice--) {
        digito = str.substr(indice, 1);
        soma += digito * peso[peso.length - str.length + indice];
    }
    soma = 11 - soma % 11;
    return soma > 9 ? 0 : soma;
}

function isValidDocument(document, tamanho, peso) {
    if (tamanho) {
        if (!document || document.length !== tamanho)
            return false;
        let raizDocument = document.substring(0, tamanho - 2);
        let digito1 = calcularDigito(raizDocument, peso);
        let digito2 = calcularDigito(raizDocument + digito1, peso);
        return document === raizDocument + digito1 + digito2;
    } else {
        return isValidCPF(document) || isValidCNPJ(document);
    }
}

function isValidCPF(cpf) {
    return isValidDocument(cpf, 11, pesoCPF);
}

function isValidCNPJ(cnpj) {
    return isValidDocument(cnpj, 14, pesoCNPJ);
}