Exibições:

 

O objetivo desse artigo é indicar um script pronto com as principais máscaras utilizadas no dia-a-dia.

Método de Alert customizado

function Alert(titulotexto)
{
    var alertStrings = { confirmButtonLabel: "Ok"text: textotitle: titulo };
    var alertOptions = { height: 120width: 260 };
    Xrm.Navigation.openAlertDialog(alertStringsalertOptions).then(
        function (success) {
            console.log("Alert dialog closed");
        },
        function (error) {
            console.log(error.message);
        }
    );
}

Método para buscar CEP através do ViaCEP

*** PARA A BUSCA DE CEP FUNCIONAR, VOCÊ PRECISA ADICIONAR O SCRIPT DE JQUERY NO FORMULÁRIO

*** ESTE MÉTODO ESTÁ APONTANDO PARA OS CAMPOS NATIVOS DO CRM, CASO VOCÊS QUEIRAM UTILIZAR EM CAMPOS DIFERENTES, SERÁ NECESSÁRIO MODIFICAR OS CAMPOS ONDE SETAMOS VALORES

function BuscarCEP(context)
{
    var cep = context.getEventSource().getValue();
    // -- Xrm.Page.getAttribute("address1_postalcode").getValue();
    //Verifica se campo cep possui valor informado.
    if (cep != null && cep != "") {
        cep = cep.replace(/[^0-9]+/g"");
        //Expressão regular para validar o CEP.
        var validacep = /^[0-9]{8}$/;
        //Valida o formato do CEP.
        if(validacep.test(cep)) {
 
            //Consulta o webservice viacep.com.br/
            $.getJSON("https://viacep.com.br/ws/"cep +"/json/?callback=?"function(dados) {
 
                if (!("erro" in dados)) {
                    //Atualiza os campos com os valores da consulta.
                    Xrm.Page.getAttribute("address1_line1").setValue(dados.logradouro);
                    Xrm.Page.getAttribute("address1_line3").setValue(dados.bairro);
                    Xrm.Page.getAttribute("address1_city").setValue(dados.localidade);
                    Xrm.Page.getAttribute("address1_stateorprovince").setValue(dados.uf);
                    // Xrm.Page.getAttribute("address1_country").setValue("Brasil");
                } 
                else{
                    Xrm.Page.getAttribute("address1_line1").setValue(null);
                    Xrm.Page.getAttribute("address1_line3").setValue(null);
                    Xrm.Page.getAttribute("address1_city").setValue(null);
                    Xrm.Page.getAttribute("address1_stateorprovince").setValue(null);
                }
            });
        } 
    }
    else
    {
        Xrm.Page.getAttribute("address1_line1").setValue(null);
        Xrm.Page.getAttribute("address1_line3").setValue(null);
        Xrm.Page.getAttribute("address1_city").setValue(null);
        Xrm.Page.getAttribute("address1_stateorprovince").setValue(null);
    } 
}

Máscara de CEP

function MascaraCep(context) {
  var oField = context.getEventSource().getValue();
  var sTmp = oField;
  if (typeof(oField) != "undefined" && oField != null) {
    sTmp = sTmp.replace(/[^0-9]+/g"");
      // sTmp = oField.replace(/[^0-9]/g, "");
      switch (sTmp.length) {
          case 8:
              sTmp = sTmp.substr(05) + "-" + sTmp.substr(53);
              break;
          default:
              Alert("Atenção""O Cep deve conter 8 caracteres.")
              break;
      }
  }
  context.getEventSource().setValue(sTmp);
}

Máscara de Telefone

function MascaraTel(context) {
  var oField = context.getEventSource().getValue();
  var sTmp = oField;
  if (typeof(oField) != "undefined" && oField != null) {
      sTmp = oField.replace(/[^0-9]+/g"");
 
          if (sTmp.length == 7) {
              sTmp = sTmp.substr(03) + "-" + sTmp.substr(34);
          } else if (sTmp.length == 8) {
              sTmp = sTmp.substr(04) + "-" + sTmp.substr(44);
          } else if (sTmp.length == 9) {
             sTmp =  sTmp.substr(05) + "-" + sTmp.substr(5,4);
          }
          else if (sTmp.length == 10) {
            sTmp = "(" + sTmp.substr(02) + ") " + sTmp.substr(2,4) + "-" + sTmp.substr(6,4);
          }
          else if (sTmp.length == 11) {
            sTmp = "(" + sTmp.substr(02) + ") " + sTmp.substr(2,5) + "-" + sTmp.substr(7,4);
          }
      
  }
  context.getEventSource().setValue(sTmp);
}

Máscara e Validação de CNPJ

function MascaraCNPJ(context) {
    var exp = /\-|\.|\/|\(|\)| /g
    var cnpjFormatado = context.getEventSource().getValue();
    if (cnpjFormatado == null) {
        return;
    }
    cnpjFormatado = cnpjFormatado.replace(/[^0-9]+/g"");
    //Somente números
    //Bloco de Código de Validação de CNPJ
    var valida = new Array(6543298765432);
    var dig1 = new Number;
    var dig2 = new Number;
    var digito = new Number(eval(cnpjFormatado.charAt(12) + cnpjFormatado.charAt(13)));
    for (i = 0i < valida.lengthi++) {
        dig1 += (i > 0 ? (cnpjFormatado.charAt(i - 1) * valida[i]) : 0);
        dig2 += cnpjFormatado.charAt(i) * valida[i];
    }
    dig1 = (((dig1 % 11) < 2) ? 0 : (11 - (dig1 % 11)));
    dig2 = (((dig2 % 11) < 2) ? 0 : (11 - (dig2 % 11)));
    if (((dig1 * 10) + dig2) != digito) {
        Alert("Validação de CNPJ""O CNPJ inserido não é válido");
        context.getEventSource().setValue(null);
    } else {
        //Formata como ##.###.###/####-##
        cnpjFormatado = cnpjFormatado.replace(exp"");
        cnpjFormatado = cnpjFormatado.substr(02) + '.' + cnpjFormatado.substr(23) + '.' + cnpjFormatado.substr(53) + '/' + cnpjFormatado.substr(84) + '-' + cnpjFormatado.substr(122);
        context.getEventSource().setValue(cnpjFormatado);
    }
}

Máscara e Validação de CPF

function MascaraCpf(context) {
    var vCPF = context.getEventSource().getValue();
    var isValid = false;
    if (vCPF != null && vCPF != "") {
        vCPF = vCPF.replace(/[^0-9]+/g"");
        vCPF = context.getEventSource().getValue().replace(/[.]/g"").replace(/[/]/g"").replace(/[-]/g"");
        var mControle = "";
        var mContIni = 2;
        mContFim = 10;
        mDigito = 0;
        for (j = 1j <= 2j++) {
            mSoma = 0;
            for (i = mContInii <= mContFimi++) mSoma = mSoma + (vCPF.substring((i - j - 1), (i - j)) * (mContFim + 1 + j - i));
            if (j == 2mSoma = mSoma + (2 * mDigito);
            mDigito = (mSoma * 10) % 11;
            if (mDigito == 10mDigito = 0;
            mControle1 = mControle;
            mControle = mDigito;
            mContIni = 3;
            mContFim = 11;
        }
        isValid = (((mControle1 * 10) + mControle) == vCPF.substring(911));
    } else {
        isValid = true;
    }
    if (!isValid) {
        Alert("Validação de CPF""O CPF inserido não é válido");
        context.getEventSource().setValue(null);
    } else {
        //Formata ###.###.###-##
        var cpfFormatado = vCPF.substr(03) + '.' + vCPF.substr(33) + '.' + vCPF.substr(63) + '-' + vCPF.substr(92);
        context.getEventSource().setValue(cpfFormatado);
    }
}
Comentários (0)