How to validate CNPJ

Asked

Viewed 1,290 times

0

I have this Submit from my form that comes from php, wanted to validate two fields within it the of cnpj and date. How to do?

$("#more").submit(function repeatLink (event) {
    event.preventDefault();

    alert('estou aqui');
    var link = $("#link").val();
    var date = $("#date-foundation").val();

    var validation = true;

    if (link === null || link === '') {
        $("#link").addClass("input-required");
        validation = false;
    }


    if (validation === true) {
        $.ajax({
            url: './model/functions/link_repeat.php',
            type: 'POST',
            data: {link: link},
            success: function (data) {
                alert(data);
                if (data === 'true') {
                    $("#link").addClass("input-required");
                    $("#alert-link").append("<span style='color:red'><b>Esse link já existe! Escolha outro!</b></span>");
                    return;
                }
            }
        });
    }
})

1 answer

2

I believe that this implementation will work. This too fiddle

It is possible to improve some parts, but I think it solves well already.

function CNPJValidator(cnpj){
	function getVerificationCode1(){
	    var total = 0;
    	var mod = 0;
        var factors = [5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2];
        var nums = this.cnpj.substr(0,12).split('');
        for( var i in nums){
        	total += nums[i]*factors[i];
        }
    	mod = total%11;
        return ( mod < 2) ? 0 : 11 - mod;
    }
    
    function getVerificationCode2(code1){
	    var total = 0;
    	var mod = 0;
        var factors = [6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2];
        var nums = (this.cnpj.substr(0,12)+code1).split('');
        for( var i in nums){
        	total += nums[i]*factors[i];
        }
    	mod = total%11;
        return ( mod < 2) ? 0 : 11 - mod;
    }
    
    this.cnpj = cnpj.replace(/[^0-9]/g, '');
    this.verificationCode1;
    this.verificationCode2;
    
    if(this.cnpj.length<14)
    	throw 'CNPJ é muito curto';
    
    this.verificationCode1 = this.cnpj.substr(-2, 1);
    this.verificationCode2 = this.cnpj.substr(-1, 1);
    
    var code1 = getVerificationCode1();
    var code2 = getVerificationCode2(code1);
    
    return code1==this.verificationCode1 && code2==this.verificationCode2;
}

console.log( CNPJValidator('11.222.333/0001-81') );
console.log( CNPJValidator('12.345.678/0001-99') );

  • Curti, returns true to 11.111.111/1111-80

  • In fact what makes a cnpj, Cpf rg, etc., valid, are the digit checkers, which are calculated based on the rest of the numbers. Roughly if the checkers match, it is because the number ta in the correct "format".

Browser other questions tagged

You are not signed in. Login or sign up in order to post.