﻿// validadores.js

// -------------------------------------------------------------
// Validadores
// Todo validador deve ter um membro 'pergunta' e um método 'validar()'
// -------------------------------------------------------------

function validadorCpf()
{
    var instance = this;
    this.pergunta = null;
    
    this.validar = function()
    {
        validarCPF(instance.pergunta.getStrValor());
    }
}
function validadorEmail()
{
    var instance = this;
    this.pergunta = null;
    
    this.validar = function()
    {
        if (!isEMail(instance.pergunta.getStrValor()))
            throw "E-mail inválido";
    }
}

// -------------------------------------------------------------
// Funções Auxiliares
// -------------------------------------------------------------
//Valida um CPF no formato 12345678901
function validarCPF(value)
{
    var strNumero = new String(value);
    if (!strNumero.match("^[0-9]{11}$")) throw "CPF inválido";
    var digito1 = calcularDigitoMod11(strNumero.substring(0, 9));
    var digito2 = calcularDigitoMod11(strNumero.substring(0, 9) + digito1);
    if (strNumero != strNumero.substring(0, 9) + digito1 + digito2)
        throw "CPF inválido";
}
//Calcula um dígito verificador usando mod 11
function calcularDigitoMod11(strNumero)
{

    if (!strNumero.match("^[0-9]*$")) throw "Número inválido.";
    var soma = 0;
    for (i = 0; i < strNumero.length; i++)
    {
        var n = parseInt(strNumero.charAt(i));
        soma += n * (strNumero.length + 1 - i);
    }
    var resto = soma % 11;
    if (resto < 2) 
        return new String(0);
    else
        return new String(11 - resto);
}
//Valida um e-mail
function isEMail(valor) 
{
	var exprEMail = /^([0-9a-zA-Z_.-]+@[0-9a-zA-Z_.-]+(.){1}[a-zA-Z]{1,4})+$/;
	return exprEMail.test( valor );
}

