​Learn to Search CPF from Clipboard

Frog JavaScript

If you're based in Brazil, you might be aware of the CPF, a legal document that's required for various official purposes. In this article, I'll show you how to validate the CPF using JavaScript and even copy it from the memory or input field.

You can also generate a valid CPF to test the code yourself here.

How it works?

We start the page with an interval reading the clipboard memory.

let intervalCpf = setInterval(() => {
    navigator.clipboard.readText()
        .then(text => {
            findValidCPFsInClipboard(text);
        })
        .catch(err => {
            console.error("Error reading clipboard:", err);
        });
}, 2000);

To use this code, the end-user needs to accept the browser to read the clipboard. We start the page with an interval reading the clipboard memory.

Give permission

When the page encounters something on the clipboard, it reads and puts it on the input field.

function findValidCPFsInClipboard(clipboardText) {
    const words = clipboardText.split(/\s+/);

    for (const word of words) {
        let strCPF = word.replaceAll('.', '').replaceAll('-', '');

        if (isValidCPF(strCPF)) {
            $("#cpf").val(maskCPF(strCPF));
            $("#isValid").text("CPF copied from memory is valid!");
            $("#isValid").show();

            clearInterval(intervalCpf);

            return true;
        }

        $("#isValid").hide();
    }

    return false;
}

The maskCpf function is called to apply the mask, which is necessary for printing the CPF number. Here's the code used to display the CPF number.

function maskCPF(cpf) {
    cpf = cpf.replace(/\D/g, '');
    cpf = cpf.replace(/(\d{3})(\d{3})(\d{3})(\d{2})/, '$1.$2.$3-$4');
    return cpf;
}

Below is the code used to validate the CPF number.

function isValidCPF(strCPF) {
    var Soma;
    var Resto;
    Soma = 0;

    if (strCPF == "00000000000") return false;

    for (i = 1; i <= 9; i++) {
        Soma = Soma + parseInt(strCPF.substring(i - 1, i)) * (11 - i);
    }
    Resto = (Soma * 10) % 11;

    if (Resto == 10 || Resto == 11) Resto = 0;
    if (Resto != parseInt(strCPF.substring(9, 10))) return false;

    Soma = 0;
    for (i = 1; i <= 10; i++) {
        Soma = Soma + parseInt(strCPF.substring(i - 1, i)) * (12 - i);
    }
    Resto = (Soma * 10) % 11;

    if (Resto == 10 || Resto == 11) Resto = 0;
    if (Resto != parseInt(strCPF.substring(10, 11))) return false;

    return true;
}

Here is it in action.

CPF Automatic

There's also a second script that reads the memory only when the input field is focused. 

$("#cpf2").focusin((e) => {
    navigator.clipboard.readText()
        .then(text => {
            const words = text.split(/\s+/);

            for (const word of words) {
                let strCPF = word.replaceAll('.', '').replaceAll('-', '');

                if (isValidCPF(strCPF)) {
                    $("#cpf2").val(maskCPF(strCPF));
                }
            }

        })
        .catch(err => {
            console.error("Error reading clipboard:", err);
        });
});

Conclusion

Filling in the CPF number manually can be tedious, especially when it's already stored in your memory. With this code, you can automate the process of copying and validating the CPF number, saving you time and effort. 

Similarly, other data like email, CEP, CNPJ, and address can also be loaded into your application and validated in the background using background Ajax code.

I hope this article has given you some ideas for making your end-users lives easier by automating tedious tasks. 

If you'd like to see the code in action, you can find it on my website at https://zoo.jsmotta.com/clipboard.

Your app can be like a frog and capture flying things.

Full source code

<!DOCTYPE html>
<html>
    <head>
        <title>Test</title>
        <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>       
        <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous">
        <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-C6RzsynM9kWDrMNeT87bh95OGNyZPhcTNXj1NW7RuBCsyN/o0jlpcV8Qyq46cDfL" crossorigin="anonymous"></script>
        <style>
            .cpf { width: 500px;}
        </style>        
    </head>
    <body>
        <a href="https:\\jsmotta.com.br" title="Jefferson's Card" target="jsm">JsM</a><br>
        <br>
        
        <label for="cpf">CPF (automatic):</label><br />
        <input id="cpf" class="cpf" placeholder="Copy to the memory a valid CPF to put here."></input>
        <br>

        <span id="isValid" style="display: none;">
        </span>
        <br><br>

        <label for="cpf2">CPF (on focus):</label><br />
        <input id="cpf2" class="cpf" placeholder="Click here to get a Cpf from memory."></input>
        <br><br> <br><br>
      

        <script> 

        $(document).ready(()=>
        {

            $("#cpf2").focusin((e) =>
            {
                navigator.clipboard.readText()
                .then(text => {
                    const words = text.split(/\s+/);      
                   
                   for (const word of words) {

                       let strCPF = word.replaceAll('.', '').replaceAll('-',''); 

                       if (isValidCPF(strCPF)) {

                           $("#cpf2").val(maskCPF(strCPF));                            
                          
                       }
                   }                 
                   
                })
                .catch(err => {
                    console.error("Error reading clipboard:", err);
                });
            });
        });

            let intervalCpf = setInterval(()=> {
                
                navigator.clipboard.readText()
                .then(text => {
                    findValidCPFsInClipboard(text);
                })
                .catch(err => {
                    console.error("Error reading clipboard:", err);
                });

            }, 2000);


    function findValidCPFsInClipboard(clipboardText) {

        const words = clipboardText.split(/\s+/);      
            
        for (const word of words) {

            let strCPF = word.replaceAll('.', '').replaceAll('-',''); 

            if (isValidCPF(strCPF)) {

                $("#cpf").val(maskCPF(strCPF));
                
                $("#isValid").text("CPF copied from memory is valid!");
                $("#isValid").show();
                
                clearInterval(intervalCpf); 
                
                return true;
            }

            $("#isValid").hide();
        }                 
        return false;
    }                  
          

    function maskCPF(cpf) { 
        cpf = cpf.replace(/\D/g, ''); 
        cpf = cpf.replace(/(\d{3})(\d{3})(\d{3})(\d{2})/, '$1.$2.$3-$4');
        return cpf;
    }
        </script>


<script>
    // https://www.devmedia.com.br/validar-cpf-com-javascript/23916
    function isValidCPF(strCPF) {
        var Soma;
        var Resto;
        Soma = 0;
       
    if (strCPF == "00000000000") return false;

    for (i=1; i<=9; i++) Soma = Soma + parseInt(strCPF.substring(i-1, i)) * (11 - i);
    Resto = (Soma * 10) % 11;

        if ((Resto == 10) || (Resto == 11))  Resto = 0;
        if (Resto != parseInt(strCPF.substring(9, 10)) ) return false;

    Soma = 0;
        for (i = 1; i <= 10; i++) Soma = Soma + parseInt(strCPF.substring(i-1, i)) * (12 - i);
        Resto = (Soma * 10) % 11;

        if ((Resto == 10) || (Resto == 11))  Resto = 0;
        if (Resto != parseInt(strCPF.substring(10, 11) ) ) return false;
        return true;
    }
</script>

<p>
    This text contains a valida CPF <br>
    number 094.939.921-36. <br><br>
    
    Copy this to the memory.      
</p>
    </body>
</html>


Similar Articles