How to validate CNPJ [duplicate]

0

I have this submit from my form that comes from php , I wanted to validate two fields within it from 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;
                }
            }
        });
    }
})
    
asked by anonymous 16.09.2016 / 13:11

1 answer

2

I believe this implementation will work. It's also on 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') );
    
16.09.2016 / 16:48