Jump to content


Photo

Mascara De Entrada


  • Faça o login para participar
61 replies to this topic

#16 Lengrat

Lengrat

    Mestre

  • Usuários
  • 638 posts
  • Sexo:Não informado

Posted 01/09/2003, 12:44

Ihhhhhhhhh...

Eu nao estou conseguindo escrever nada nos campos.
:(

#17 Lengrat

Lengrat

    Mestre

  • Usuários
  • 638 posts
  • Sexo:Não informado

Posted 01/09/2003, 12:46

Eu hein.... fechei a budega toda a arbri novamente,
Agora funfoooooooooooooooooooou :P

Mau sapão, mau sapão :D

Agora para data, tem uma deficiência grave...
Como é que eu posso validar se o mês que o infeliz for preencher
está entre 1 a 12, e coloca data com 2 digitos ao inves de 4 e um dia maior que 31?

Vai que o nego preenche uma data errônea 54/13/20,
Como é que fica? (Acreditem..existem usuarios Espírito de Porco que adora fazer isto. Quando eu quero testar a validação de um determinado formulario de um determinado site, eu faço isso..ehehehehehe )

Andei pensando e acho que para validar data só vai ficar eficiente
se tiver 3 edits separados, um para dia, outro para mês e outro para ano.
Só assim dará para verificar os dados informados corretamente.

Dai joga os valores numa String de caracteres e temos a data certinha.
Só que dá um sono só de pensar neste trabalhao todo :P

Cs tem um modo mais rapido naum?

:ok:

#18 Guest

Guest
  • Visitantes

Posted 18/09/2003, 17:18

Pra vcs aprenderem a trabalhar com mascara de entrada...


<html> 
<head> 
<title>Máscaras para Formulários</title> 
<script language="JavaScript"> 
/*** 
* Descrição.: formata um campo do formulário de 
* acordo com a máscara informada... 
* Parâmetros: - objForm (o Objeto Form) 
* - strField (string contendo o nome 
* do textbox) 
* - sMask (mascara que define o 
* formato que o dado será apresentado, 
* usando o algarismo "9" para 
* definir números e o símbolo "!" para 
* qualquer caracter... 
* - evtKeyPress (evento) 
* Uso.......: <input type="textbox" 
* name="xxx"..... 
* onkeypress="return txtBoxFormat(document.rcfDownload, 'str_cep', '99999-999', event);"> 
* Observação: As máscaras podem ser representadas como os exemplos abaixo: 
* CEP -> 99.999-999 
* CPF -> 999.999.999-99 
* CNPJ -> 99.999.999/9999-99 
* Data -> 99/99/9999 
* Tel Resid -> (99) 999-9999 
* Tel Cel -> (99) 9999-9999 
* Processo -> 99.999999999/999-99 
* C/C -> 999999-! 
* E por aí vai... 
***/

function txtBoxFormat(objForm, strField, sMask, evtKeyPress) {
      var i, nCount, sValue, fldLen, mskLen,bolMask, sCod, nTecla;

      if(document.all) { // Internet Explorer
        nTecla = evtKeyPress.keyCode; }
      else if(document.layers) { // Nestcape
        nTecla = evtKeyPress.which;
      }

      sValue = objForm[strField].value;

      // Limpa todos os caracteres de formatação que
      // já estiverem no campo.
      sValue = sValue.toString().replace( "-", "" );
      sValue = sValue.toString().replace( "-", "" );
      sValue = sValue.toString().replace( ".", "" );
      sValue = sValue.toString().replace( ".", "" );
      sValue = sValue.toString().replace( "/", "" );
      sValue = sValue.toString().replace( "/", "" );
      sValue = sValue.toString().replace( "(", "" );
      sValue = sValue.toString().replace( "(", "" );
      sValue = sValue.toString().replace( ")", "" );
      sValue = sValue.toString().replace( ")", "" );
      sValue = sValue.toString().replace( " ", "" );
      sValue = sValue.toString().replace( " ", "" );
      fldLen = sValue.length;
      mskLen = sMask.length;

      i = 0;
      nCount = 0;
      sCod = "";
      mskLen = fldLen;

      while (i <= mskLen) {
        bolMask = ((sMask.charAt(i) == "-") || (sMask.charAt(i) == ".") || (sMask.charAt(i) == "/"))
        bolMask = bolMask || ((sMask.charAt(i) == "(") || (sMask.charAt(i) == ")") || (sMask.charAt(i) == " "))

        if (bolMask) {
          sCod += sMask.charAt(i);
          mskLen++; }
        else {
          sCod += sValue.charAt(nCount);
          nCount++;
        }

        i++;
      }

      objForm[strField].value = sCod;

      if (nTecla != 8) { // backspace
        if (sMask.charAt(i-1) == "9") { // apenas números...
          return ((nTecla > 47) && (nTecla < 58)); } // números de 0 a 9
        else { // qualquer caracter...
          return true;
        } }
      else {
        return true;
      }
    }
//Fim da Função Máscaras Gerais
</script>
</head> 
<body> 
<font size="2" face="Verdana, Arial, Helvetica, sans-serif"><strong>Formatação 
de várias Máscaras de Entradas para campos de Formulários</strong></font> 
<form name="Form"> 
<table border="0" cellspacing="2" cellpadding="2"> 
<tr> 
<td width="66"><font size="2" face="Verdana, Arial, Helvetica, sans-serif">Cep 
&nbsp;</font></td> 
<td width="128"> <input type="text" 
name="str_cep" 
maxlength="10" 
size="10" 
onkeypress="return txtBoxFormat(document.Form, 'str_cep', '99.999-999', event);"> 
</td> 
</tr> 
<tr> 
<td><font size="2" face="Verdana, Arial, Helvetica, sans-serif">Cpf &nbsp;</font></td> 
<td> <input type="text" 
name="str_cpf" 
maxlength="14" 
size="14" 
onkeypress="return txtBoxFormat(document.Form, 'str_cpf', '999.999.999-99', event);"> 
</td> 
</tr> 
<tr> 
<td><font size="2" face="Verdana, Arial, Helvetica, sans-serif">Cnpj</font></td> 
<td><input type="text" 
name="str_cnpj" 
maxlength="18" 
size="18" 
onkeypress="return txtBoxFormat(document.Form, 'str_cnpj', '99.999.999/9999-99', event);"></td> 
</tr> 
<tr> 
<td><font size="2" face="Verdana, Arial, Helvetica, sans-serif">Data</font></td> 
<td><input type="text" 
name="str_data" 
maxlength="10" 
size="10" 
onkeypress="return txtBoxFormat(document.Form, 'str_data', '99/99/9999', event);"></td> 
</tr> 
<tr> 
<td><font size="2" face="Verdana, Arial, Helvetica, sans-serif">Tel Resid</font></td> 
<td><input type="text" 
name="str_tel2" 
maxlength="13" 
size="13" 
onkeypress="return txtBoxFormat(document.Form, 'str_tel2', '(99) 999-9999', event);"></td> 
</tr> 
<tr> 
<td><font size="2" face="Verdana, Arial, Helvetica, sans-serif">Tel Cel&nbsp;</font></td> 
<td> <input type="text" 
name="str_tel" 
maxlength="14" 
size="14" 
onkeypress="return txtBoxFormat(document.Form, 'str_tel', '(99) 9999-9999', event);"> 
</td> 
</tr> 
<tr> 
<td><font size="2" face="Verdana, Arial, Helvetica, sans-serif">Processo</font></td> 
<td><input type="text" 
name="str_proc" 
maxlength="20" 
size="20" 
onkeypress="return txtBoxFormat(document.Form, 'str_proc', '99.999999999/9999-99', event);"></td> 
</tr> 
<tr> 
<td><font size="2" face="Verdana, Arial, Helvetica, sans-serif">Conta &nbsp;</font></td> 
<td> <input type="text" 
name="str_cc" 
maxlength="6" 
size="10" 
onkeypress="return txtBoxFormat(document.Form, 'str_cc', '9999-!', event);"> 
</td> 
</tr> 
</table> 
</form> 
</body> 
</html>

:)
Ola Cristiano, queria saber se tem jeito de comocar um botao radio para delinir qua e o cpf e o cgc, pois qualdo o usuario clicar no radio cpf ele dijitara o numero do cpf e assi do cgc.

tem como.
grato

#19 marco_info

marco_info

    Novato no fórum

  • Usuários
  • 23 posts
  • Sexo:Não informado

Posted 19/08/2004, 11:41

Ola Estou precisando de ajuda com esse script de mascara de data !!

tenhu um form chamado "form1" e um campo chamado "prefeito_data2" ja coloquei corretamente na chamada da funçao. so que ele ve volta um erro de "undefined".............tenhu outros scripts nessa pagina.......será que isso influi ??

preciso terminar isso !!! helpp !

desde ja agradeço

#20 varralde

varralde

    Novato no fórum

  • Usuários
  • 21 posts
  • Sexo:Não informado

Posted 27/02/2005, 02:03

Muito bom o código, tá funcionando blz para mim

#21 arthurlucena

arthurlucena

    Imamade nandomo..

  • Usuários
  • 343 posts
  • Sexo:Masculino
  • Localidade:João Pessoa
  • Interesses:Desenho, artes gráficas, fotografia, games, praia, cinema, animes, cultura japonesa, tecnologia, desenvolvimento para web entre outras coisas =)

Posted 09/08/2005, 16:18

Bom, essas máscaras não funcionaram aqui no FIrefox. No IE, sim, funcionaram perfeitamente =)

Eu estava procurando por isso mesmo.

No entanto, alguém aqui saberia fazer a "versao" para Firefox?


Fico no aguardo
...........darkness.........²d¬¬b²
A vida é muito curta para se preocupar com o que as outras pessoas pensam. Viva.
Arthur Lucena..................貴族
arthurlucena at email dot com
[O'']olhares.com/arthurlucena

#22 redstyle

redstyle

    Expert

  • Usuários
  • 540 posts
  • Sexo:Masculino

Posted 11/08/2005, 16:57

Bom, essas máscaras não funcionaram aqui no FIrefox. No IE, sim, funcionaram perfeitamente =)

Eu estava procurando por isso mesmo.

No entanto, alguém aqui saberia fazer a "versao" para Firefox?


Fico no aguardo

Compatível com IE & Firefox

- Tirei um parâmetro da função por que agora ele pega pelo id do input utilizando getElementById()
- Coloquei um if pra verificar se a tecla apertada é o backspace e se for não faz nada e deixa a pessoa ir apagando

- Ainda não achei uma maneira de deixar a pessoa apagar somente um caractere do meio e na hora que inserir o caractere não ir pro último lugar.

Abraços.

<html>
<head>
<title>Máscaras para Formulários</title>
<script language="JavaScript">
/***
* Descrição.: formata um campo do formulário de
* acordo com a máscara informada...
* Parâmetros: - objForm (o Objeto Form)
* - strField (string contendo o nome
* do textbox)
* - sMask (mascara que define o
* formato que o dado será apresentado,
* usando o algarismo "9" para
* definir números e o símbolo "!" para
* qualquer caracter...
* - evtKeyPress (evento)
* Uso.......: <input type="textbox"
* name="xxx".....
* onkeypress="return txtBoxFormat(document.rcfDownload, 'str_cep', '99999-999', event);">
* Observação: As máscaras podem ser representadas como os exemplos abaixo:
* CEP -> 99.999-999
* CPF -> 999.999.999-99
* CNPJ -> 99.999.999/9999-99
* Data -> 99/99/9999
* Tel Resid -> (99) 999-9999
* Tel Cel -> (99) 9999-9999
* Processo -> 99.999999999/999-99
* C/C -> 999999-!
* E por aí vai...
***/

function txtBoxFormat(strField, sMask, evtKeyPress) {
     var i, nCount, sValue, fldLen, mskLen,bolMask, sCod, nTecla;

     if(window.event) { // Internet Explorer
       nTecla = evtKeyPress.keyCode; }
     else if(evtKeyPress.which) { // Nestcape / firefox
       nTecla = evtKeyPress.which;
     }
	//se for backspace não faz nada
	if (nTecla != 8){
     sValue = document.getElementById(strField).value;
	// alert(sValue);

     // Limpa todos os caracteres de formatação que
     // já estiverem no campo.
     sValue = sValue.toString().replace( "-", "" );
     sValue = sValue.toString().replace( "-", "" );
     sValue = sValue.toString().replace( ".", "" );
     sValue = sValue.toString().replace( ".", "" );
     sValue = sValue.toString().replace( "/", "" );
     sValue = sValue.toString().replace( "/", "" );
     sValue = sValue.toString().replace( "(", "" );
     sValue = sValue.toString().replace( "(", "" );
     sValue = sValue.toString().replace( ")", "" );
     sValue = sValue.toString().replace( ")", "" );
     sValue = sValue.toString().replace( " ", "" );
     sValue = sValue.toString().replace( " ", "" );
     fldLen = sValue.length;
     mskLen = sMask.length;

     i = 0;
     nCount = 0;
     sCod = "";
     mskLen = fldLen;

     while (i <= mskLen) {
       bolMask = ((sMask.charAt(i) == "-") || (sMask.charAt(i) == ".") || (sMask.charAt(i) == "/"))
       bolMask = bolMask || ((sMask.charAt(i) == "(") || (sMask.charAt(i) == ")") || (sMask.charAt(i) == " "))

       if (bolMask) {
         sCod += sMask.charAt(i);
         mskLen++; }
       else {
         sCod += sValue.charAt(nCount);
         nCount++;
       }

       i++;
     }

     document.getElementById(strField).value = sCod;

     if (nTecla != 8) { // backspace
       if (sMask.charAt(i-1) == "9") { // apenas números...
         return ((nTecla > 47) && (nTecla < 58)); } // números de 0 a 9
       else { // qualquer caracter...
         return true;
       } }
     else {
       return true;
     }
	}//fim do if que verifica se é backspace
}
//Fim da Função Máscaras Gerais
</script>
</head>
<body>
<font size="2" face="Verdana, Arial, Helvetica, sans-serif"><strong>Formatação
de várias Máscaras de Entradas para campos de Formulários</strong></font>
<form name="Form">
<table border="0" cellspacing="2" cellpadding="2">
<tr>
<td width="66"><font size="2" face="Verdana, Arial, Helvetica, sans-serif">Cep
&nbsp;</font></td>
<td width="128"> <input type="text"
name="str_cep"
maxlength="10"
size="10"
id="str_cep" 
onKeyPress="return txtBoxFormat('str_cep', '99.999-999', event);">
</td>
</tr>
<tr>
<td><font size="2" face="Verdana, Arial, Helvetica, sans-serif">Cpf &nbsp;</font></td>
<td> <input type="text"
name="str_cpf"
maxlength="14"
size="14" 
id="str_cpf" 
onkeypress="return txtBoxFormat('str_cpf', '999.999.999-99', event);">
</td>
</tr>
<tr>
<td><font size="2" face="Verdana, Arial, Helvetica, sans-serif">Cnpj</font></td>
<td><input type="text"
name="str_cnpj"
maxlength="18"
size="18"
id="str_cnpj" 
onkeypress="return txtBoxFormat('str_cnpj', '99.999.999/9999-99', event);"></td>
</tr>
<tr>
<td><font size="2" face="Verdana, Arial, Helvetica, sans-serif">Data</font></td>
<td><input type="text"
name="str_data"
maxlength="10"
size="10" 
id="str_data" 
onkeypress="return txtBoxFormat('str_data', '99/99/9999', event);"></td>
</tr>
<tr>
<td><font size="2" face="Verdana, Arial, Helvetica, sans-serif">Tel Resid</font></td>
<td><input type="text"
name="str_tel2"
maxlength="13"
size="13"
id="str_tel2" 
onkeypress="return txtBoxFormat('str_tel2', '(99) 999-9999', event);"></td>
</tr>
<tr>
<td><font size="2" face="Verdana, Arial, Helvetica, sans-serif">Tel Cel&nbsp;</font></td>
<td> <input type="text"
name="str_tel"
maxlength="14"
size="14" 
id="str_tel" 
onkeypress="return txtBoxFormat('str_tel', '(99) 9999-9999', event);">
</td>
</tr>
<tr>
<td><font size="2" face="Verdana, Arial, Helvetica, sans-serif">Processo</font></td>
<td><input type="text"
name="str_proc"
maxlength="20"
size="20" 
id="str_proc" 
onkeypress="return txtBoxFormat('str_proc', '99.999999999/9999-99', event);"></td>
</tr>
<tr>
<td><font size="2" face="Verdana, Arial, Helvetica, sans-serif">Conta &nbsp;</font></td>
<td> <input type="text"
name="str_cc"
maxlength="6"
size="10" 
id="str_cc"  
onkeypress="return txtBoxFormat('str_cc', '9999-!', event);">
</td>
</tr>
</table>
</form>
</body>
</html>

Edição feita por: redstyle, 11/08/2005, 17:24.

Conheça meu blog para Aprender Laravel (Framework PHP)


#23 francisco

francisco

    Novato no fórum

  • Usuários
  • 1 posts
  • Sexo:Não informado

Posted 14/09/2005, 09:32

Fiz uma adaptação do código para aceitar mascara de hora


<html>
<head>
<title>Máscaras para Formulários</title>
<script language="JavaScript">
/***
* Descrição.: formata um campo do formulário de
* acordo com a máscara informada...
* Parâmetros: - objForm (o Objeto Form)
* - strField (string contendo o nome
* do textbox)
* - sMask (mascara que define o
* formato que o dado será apresentado,
* usando o algarismo "9" para
* definir números e o símbolo "!" para
* qualquer caracter...
* - evtKeyPress (evento)
* Uso.......: <input type="textbox"
* name="xxx".....
* onkeypress="return txtBoxFormat(document.rcfDownload, 'str_cep', '99999-999', event);">
* Observação: As máscaras podem ser representadas como os exemplos abaixo:
* CEP -> 99.999-999
* CPF -> 999.999.999-99
* CNPJ -> 99.999.999/9999-99
* Data -> 99/99/9999
* Tel Resid -> (99) 999-9999
* Tel Cel -> (99) 9999-9999
* Processo -> 99.999999999/999-99
* C/C -> 999999-!
* Hora -> 99:99:99
* E por aí vai...
***/

function txtBoxFormat(objForm, strField, sMask, evtKeyPress) {
var i, nCount, sValue, fldLen, mskLen,bolMask, sCod, nTecla;

if(document.all) { // Internet Explorer
nTecla = evtKeyPress.keyCode; }
else if(document.layers) { // Nestcape
nTecla = evtKeyPress.which;
}

sValue = objForm[strField].value;

// Limpa todos os caracteres de formatação que
// já estiverem no campo.
sValue = sValue.toString().replace( "-", "" );
sValue = sValue.toString().replace( "-", "" );
sValue = sValue.toString().replace( ".", "" );
sValue = sValue.toString().replace( ".", "" );
sValue = sValue.toString().replace( "/", "" );
sValue = sValue.toString().replace( "/", "" );
sValue = sValue.toString().replace( "(", "" );
sValue = sValue.toString().replace( "(", "" );
sValue = sValue.toString().replace( ")", "" );
sValue = sValue.toString().replace( ")", "" );
sValue = sValue.toString().replace( " ", "" );
sValue = sValue.toString().replace( " ", "" );
sValue = sValue.toString().replace( ":", "" );
sValue = sValue.toString().replace( ":", "" );
fldLen = sValue.length;
mskLen = sMask.length;

i = 0;
nCount = 0;
sCod = "";
mskLen = fldLen;

while (i <= mskLen) {
bolMask = ((sMask.charAt(i) == "-") || (sMask.charAt(i) == ".") || (sMask.charAt(i) == "/"))
bolMask = bolMask || ((sMask.charAt(i) == "(") || (sMask.charAt(i) == ")") || (sMask.charAt(i) == " ") || (sMask.charAt(i) == ":"))

if (bolMask) {
sCod += sMask.charAt(i);
mskLen++; }
else {
sCod += sValue.charAt(nCount);
nCount++;
}

i++;
}

objForm[strField].value = sCod;

if (nTecla != 8) { // backspace
if (sMask.charAt(i-1) == "9") { // apenas números...
return ((nTecla > 47) && (nTecla < 58)); } // números de 0 a 9
else { // qualquer caracter...
return true;
} }
else {
return true;
}
}
//Fim da Função Máscaras Gerais
</script>
</head>
<body>
<font size="2" face="Verdana, Arial, Helvetica, sans-serif"><strong>Formatação
de várias Máscaras de Entradas para campos de Formulários</strong></font>
<form name="Form">
<table border="0" cellspacing="2" cellpadding="2">
<tr>
<td width="66"><font size="2" face="Verdana, Arial, Helvetica, sans-serif">Cep
&nbsp;</font></td>
<td width="128"> <input type="text"
name="str_cep"
maxlength="10"
size="10"
onkeypress="return txtBoxFormat(document.Form, 'str_cep', '99.999-999', event);">
</td>
</tr>
<tr>
<td><font size="2" face="Verdana, Arial, Helvetica, sans-serif">Cpf &nbsp;</font></td>
<td> <input type="text"
name="str_cpf"
maxlength="14"
size="14"
onkeypress="return txtBoxFormat(document.Form, 'str_cpf', '999.999.999-99', event);">
</td>
</tr>
<tr>
<td><font size="2" face="Verdana, Arial, Helvetica, sans-serif">Cnpj</font></td>
<td><input type="text"
name="str_cnpj"
maxlength="18"
size="18"
onkeypress="return txtBoxFormat(document.Form, 'str_cnpj', '99.999.999/9999-99', event);"></td>
</tr>
<tr>
<td><font size="2" face="Verdana, Arial, Helvetica, sans-serif">Data</font></td>
<td><input type="text"
name="str_data"
maxlength="10"
size="10"
onkeypress="return txtBoxFormat(document.Form, 'str_data', '99/99/9999', event);"></td>
</tr>
<tr>
<td><font size="2" face="Verdana, Arial, Helvetica, sans-serif">Tel Resid</font></td>
<td><input type="text"
name="str_tel2"
maxlength="13"
size="13"
onkeypress="return txtBoxFormat(document.Form, 'str_tel2', '(99) 999-9999', event);"></td>
</tr>
<tr>
<td><font size="2" face="Verdana, Arial, Helvetica, sans-serif">Tel Cel&nbsp;</font></td>
<td> <input type="text"
name="str_tel"
maxlength="14"
size="14"
onkeypress="return txtBoxFormat(document.Form, 'str_tel', '(99) 9999-9999', event);">
</td>
</tr>
<tr>
<td><font size="2" face="Verdana, Arial, Helvetica, sans-serif">Processo</font></td>
<td><input type="text"
name="str_proc"
maxlength="20"
size="20"
onkeypress="return txtBoxFormat(document.Form, 'str_proc', '99.999999999/9999-99', event);"></td>
</tr>
<tr>
<td><font size="2" face="Verdana, Arial, Helvetica, sans-serif">Conta &nbsp;</font></td>
<td> <input type="text" name="str_cc" maxlength="6" size="10" onkeypress="return txtBoxFormat(document.Form, 'str_cc', '9999-!', event);">
</td>
</tr>
<tr>
<td><font size="2" face="Verdana, Arial, Helvetica, sans-serif">Hora &nbsp;</font></td>
<td> <input type="text" name="str_hora" maxlength="8" size="10" onkeypress="return txtBoxFormat(document.Form, 'str_hora', '99:99:99', event);">
</td>
</tr>
</table>
</form>
</body>
</html>

#24 ride

ride

    12 Horas

  • Usuários
  • 131 posts
  • Sexo:Não informado

Posted 08/12/2005, 16:35

só dando um ajuste. no lugar de

sValue = sValue.toString().replace( "-", "" );
sValue = sValue.toString().replace( "-", "" );
sValue = sValue.toString().replace( ".", "" );
sValue = sValue.toString().replace( ".", "" );
sValue = sValue.toString().replace( "/", "" );
sValue = sValue.toString().replace( "/", "" );
sValue = sValue.toString().replace( "(", "" );
sValue = sValue.toString().replace( "(", "" );
sValue = sValue.toString().replace( ")", "" );
sValue = sValue.toString().replace( ")", "" );
sValue = sValue.toString().replace( " ", "" );
sValue = sValue.toString().replace( " ", "" );

pode-se trocar por

expressao = /[\.\/\-\(\) ]/gi;
sValue = sValue.toString().replace(expressao, '');

e valeu, esse script esta bem útil.
http://centralti.com

#25 Ricardo Ziglio

Ricardo Ziglio
  • Visitantes

Posted 08/04/2006, 11:25

Eu dei uma melhorada no codigo...
Coletei umas dicas nesse topico.
Acrescentei as mascaras , e ;
Colequei x q pode ser apenas letra, e sem dar espaço...

exemplo:
Placa de carro -> xxx - 9999

Mudei uma linha agora tá rodando no i.e e firefox

Também achei um bug mais não consegui corrigir...
O bug é o seguinte exemplo:
mascara '9999-!'
se vc já estiver no 9999-
dai selecionar esse 9999-
depois digitar A
no campo vc tera o reseultado "A" na 1° posição
ou seja quebrou a consistencia da mascara ...

Agora segue a versão q ajeitei:
<html>
<head>
<title>Máscaras para Formulários</title>
<script language="JavaScript">
/***
* Descrição.: formata um campo do formulário de acordo com a máscara informada...
* Parâmetros: 
* - objForm (o Objeto Form)
* - strField (string contendo o nome do textbox)
* - sMask (mascara que define o  formato que o dado será apresentado:
* "9" para definir números 
* "x" para definir somente letras maiusculas e minusculas SEM espaço
* "!" para qualquer caracter
*
* - evtKeyPress (evento)
* Uso...: <input type="textbox"
* name="xxx".....
* onkeypress="return txtBoxFormat(document.rcfDownload, 'str_cep', '99999-999', event);">
*
* Caracteres aceitos para mascara : -,;:./() espaço
* 
* Observação: As máscaras podem ser representadas como os exemplos abaixo:
* CEP -> 99.999-999
* CPF -> 999.999.999-99
* CNPJ -> 99.999.999/9999-99
* Data -> 99/99/9999
* Tel Resid -> (99) 999-9999
* Tel Cel -> (99) 9999-9999
* Processo -> 99.999999999/999-99
* C/C -> 999999-!
* Hora -> 99:99:99 
* Placa -> xxx - 9999
***/

function txtBoxFormat(objForm, strField, sMask, evtKeyPress) {
	 var i, nCount, sValue, fldLen, mskLen,bolMask, sCod, nTecla;
	 nTecla = (evtKeyPress.which) ? evtKeyPress.which : evtKeyPress.keyCode;
	 sValue = objForm[strField].value;
	 // Limpa todos os caracteres de formatação que
	 // já estiverem no campo.
	 expressao = /[\.\/\-\(\)\,\;\: ]/gi;
	 sValue = sValue.toString().replace(expressao, '');
	 fldLen = sValue.length;
	 mskLen = sMask.length;

	 i = 0;
	 nCount = 0;
	 sCod = "";
	 mskLen = fldLen;

	 while (i <= mskLen) {
	   bolMask = ((sMask.charAt(i) == "-") || (sMask.charAt(i) == ".") || (sMask.charAt(i) == "/") || (sMask.charAt(i) == ",") || (sMask.charAt(i) == ";") || (sMask.charAt(i) == ":"))
	   bolMask = bolMask || ((sMask.charAt(i) == "(") || (sMask.charAt(i) == ")") || (sMask.charAt(i) == " "))

	   if (bolMask) {
		 sCod += sMask.charAt(i);
		 mskLen++; }
	   else {
		 sCod += sValue.charAt(nCount);
		 nCount++;
	   }

	   i++;
	 }

	 objForm[strField].value = sCod;

	 if (nTecla != 8 && nTecla != 13)
	  { // backspace enter
	   if (sMask.charAt(i-1) == "9") 
	   { // apenas números...
		 return ((nTecla > 47) && (nTecla < 58)); 
	   } // números de 0 a 9
	   else 
	   { 
			if (sMask.charAt(i-1) == "x") 
		   { // apenas letras... Sem espaco
			 return ((nTecla > 64) && (nTecla < 123)); 
		   } // maiusculas e minusculas de A a z sem acentos
		   else 
		   { // qualquer caracter...
			return true;
		  } 
	   } 
	  }
	 else 
	 {
	   return true;
	 }
   }
//Fim da Função Máscaras Gerais
</script>
</head>
<body>
<font size="2" face="Verdana, Arial, Helvetica, sans-serif"><strong>Formatação
de várias Máscaras de Entradas para campos de Formulários</strong></font>
<form name="Form">
<table border="0" cellspacing="2" cellpadding="2">
<tr>
<td width="66"><font size="2" face="Verdana, Arial, Helvetica, sans-serif">Cep
&nbsp;</font></td>
<td width="128"> <input type="text"
name="str_cep"
maxlength="10"
size="10"
onkeypress="return txtBoxFormat(document.Form, 'str_cep', '99.999-999', event);">
</td>
</tr>
<tr>
<td><font size="2" face="Verdana, Arial, Helvetica, sans-serif">Cpf &nbsp;</font></td>
<td> <input type="text"
name="str_cpf"
maxlength="14"
size="14"
onkeypress="return txtBoxFormat(document.Form, 'str_cpf', '999.999.999-99', event);">
</td>
</tr>
<tr>
<td><font size="2" face="Verdana, Arial, Helvetica, sans-serif">Cnpj</font></td>
<td><input type="text"
name="str_cnpj"
maxlength="18"
size="18"
onkeypress="return txtBoxFormat(document.Form, 'str_cnpj', '99.999.999/9999-99', event);"></td>
</tr>
<tr>
<td><font size="2" face="Verdana, Arial, Helvetica, sans-serif">Data</font></td>
<td><input type="text"
name="str_data"
maxlength="10"
size="10"
onkeypress="return txtBoxFormat(document.Form, 'str_data', '99/99/9999', event);"></td>
</tr>
<tr>
<td><font size="2" face="Verdana, Arial, Helvetica, sans-serif">Tel Resid</font></td>
<td><input type="text"
name="str_tel2"
maxlength="13"
size="13"
onkeypress="return txtBoxFormat(document.Form, 'str_tel2', '(99) 999-9999', event);"></td>
</tr>
<tr>
<td><font size="2" face="Verdana, Arial, Helvetica, sans-serif">Tel Cel&nbsp;</font></td>
<td> <input type="text"
name="str_tel"
maxlength="14"
size="14"
onkeypress="return txtBoxFormat(document.Form, 'str_tel', '(99) 9999-9999', event);">
</td>
</tr>
				<tr>
<td><font size="2" face="Verdana, Arial, Helvetica, sans-serif">Processo</font></td>
<td><input type="text"
name="str_proc"
maxlength="20"
size="20"
onkeypress="return txtBoxFormat(document.Form, 'str_proc', '99.999999999/9999-99', event);"></td>
</tr>
				<tr>
					<td><font size="2" face="Verdana, Arial, Helvetica, sans-serif">Conta &nbsp;</font></td>
					<td><input type="text"
name="str_cc"
maxlength="6"
size="10"
onkeypress="return txtBoxFormat(document.Form, 'str_cc', '9999-!', event);"></td>
				</tr>
				<tr>
					<td>Hora</td>
					<td><input type="text" name="hora" maxlength="8" size="8" onkeypress="return txtBoxFormat(document.Form, 'hora', '99:99:99', event);"></td>
				</tr>
				<tr>
					<td>Placa</td>
					<td><input type="text" name="placa" maxlength="10" size="10" 
onkeypress="return txtBoxFormat(document.Form, 'placa', 'xxx - 9999', event);"></td>
				</tr>
			</table>
			<input type="text" name="a" id="a" onkeypress="k = (event.which) ? event.which : event.keyCode;alert(k);">
		</form>
</body>
</html>

Edição feita por: Ricardo Ziglio, 08/04/2006, 11:36.


#26 redstyle

redstyle

    Expert

  • Usuários
  • 540 posts
  • Sexo:Masculino

Posted 08/04/2006, 14:48

Galera nesse site tem um esquema de mascara muito bom, além de mais um monte de coisa que ajuda em javascript.

http://jsfromhell.com/forms/restrict

esse outro site é um biblioteca pra validar form. Muito boa.

http://yav.sourceforge.net/

Falowz

Conheça meu blog para Aprender Laravel (Framework PHP)


#27 portalwebmaster

portalwebmaster

    kd as minas???

  • Usuários
  • 137 posts
  • Sexo:Não informado
  • Localidade:São Paulo - SP

Posted 27/04/2006, 00:49

eu copiei este cod e fiz um teste nele aki..

seguinte ele faz tudo certinho, más minha dúvida é o seguinte...

faça um teste escreva no campo cep por exemplo e depois q terminar de escrever, vamos supor que vc errou o cep ai vc quer apagar, quando vc aperta o backespace para ir apagando, quando chega em um dos caracters que o js colocou ele não deixa apagar...

será que tem como fazer ele permitir que seja apagado tudo?

#28 Andreia Regina

Andreia Regina

    Veterano

  • Conselheiros
  • 1347 posts
  • Sexo:Feminino
  • Localidade:PR
  • Interesses:PHP; MySQL; Javascript; CSS; tudo ligado ao desenvolvimento web.

Posted 27/04/2006, 11:52

Oi!

Vc viu o link que o redstyle passou? lá mesmo vc pode testar ele apaga os caracteres.

Fórum WMO - Conselheira - Na equipe desde 31/01/2006.
Links importantes: Regras de conduta - Busca do fórum


#29 mbtec

mbtec

    Novato no fórum

  • Usuários
  • 2 posts
  • Sexo:Masculino

Posted 03/07/2006, 10:11

Galera nesse site tem um esquema de mascara muito bom, além de mais um monte de coisa que ajuda em javascript.

http://jsfromhell.com/forms/restrict

esse outro site é um biblioteca pra validar form. Muito boa.

http://yav.sourceforge.net/

Falowz


Caros Amigos,

Referente este link mencionado acima, estou recebendo o seguinte erro:

*** Parse error: parse error, unexpected '=' in /var/www/gerencia/cadastra_contratos_mask.php on line 23***


Segue em anexo meu código, caso puderem me auxiliar, obrigado.

<?

**************************************
* Restrict Class v1.0 *
* Autor: Carlos R. L. Rodrigues *
**************************************
*/

//========================================================
// REQUIRES http://www.jsfromhel.../event-listener
//========================================================

Restrict = function(cadcon){
this.form = form, this.field = {}, this.mask = {};
}
Restrict.field = Restrict.inst = Restrict.c = null;
Restrict.prototype.start = function(){
var $, __ = document.forms[this.form], s, x, j, c, sp, o = this, l;
var p = {".":/./, w:/\w/, W:/\W/, d:/\d/, D:/\D/, s:/\s/, a:/[\xc0-\xff]/, A:/[^\xc0-\xff]/};
for(var _ in $ = this.field)
if(/text|textarea|password/i.test(__[_].type)){
x = $[_].split(""), c = j = 0, sp, s = [[],[]];
for(var i = 0, l = x.length; i < l; i++)
if(x[i] == "\\" || sp){
if(sp = !sp) continue;
s[j][c++] = p[x[i]] || x[i];
}
else if(x[i] == "^") c = (j = 1) - 1;
else s[j][c++] = x[i];
o.mask[__[_].name] && (__[_].maxLength = o.mask[__[_].name].length);
__[_].pt = s, addEvent(__[_], "keydown", function(e){
var r = Restrict.field = e.target;
if(!o.mask[r.name]) return;
r.l = r.value.length, Restrict.inst = o; Restrict.c = e.key;
setTimeout(o.onchanged, r.e = 1);
});
addEvent(__[_], "keyup", function(e){
(Restrict.field = e.target).e = 0;
});
addEvent(__[_], "keypress", function(e){
o.restrict(e) || e.preventDefault();
var r = Restrict.field = e.target;
if(!o.mask[r.name]) return;
if(!r.e){
r.l = r.value.length, Restrict.inst = o, Restrict.c = e.key || 0;
setTimeout(o.onchanged, 1);
?Û }
});
}
}
Restrict.prototype.restrict = function(e){
var o, c = e.key, n = (o = e.target).name, r;
var has = function(c, r){
for(var i = r.length; i--;)
if((r[i] instanceof RegExp && r[i].test©) || r[i] == c) return true;
return false;
}
var inRange = function©{
return has(c, o.pt[0]) && !has(c, o.pt[1]);
}
return (c < 30 || inRange(String.fromCharCode©)) ?
(this.onKeyAccept && this.onKeyAccept(o, c), !0) :
(this.onKeyRefuse && this.onKeyRefuse(o, c), !1);
}
Restrict.prototype.onchanged = function(){
var ob = Restrict, si, moz = false, o = ob.field, t, lt = (t = o.value).length, m = ob.inst.mask[o.name];
if(o.l == o.value.length) return;
if(si = o.selectionStart) moz = true;
else if(o.createTextRange){
var obj = document.selection.createRange(), r = o.createTextRange();
if(!r.setEndPoint) return false;
r.setEndPoint("EndToStart", obj); si = r.text.length;
}
else return false;
for(var i in m = m.split(""))
if(m[i] != "#")
t = t.replace(m[i] == "\\" ? m[++i] : m[i], "");
var j = 0, h = "", l = m.length, ini = si == 1, t = t.split("");
for(i = 0; i < l; i++)
if(m[i] != "#"){
if(m[i] == "\\" && (h += m[++i])) continue;
h += m[i], i + 1 == l && (t[j - 1] += h, h = "");
}
else{
if(!t[j] && !(h = "")) break;
(t[j] = h + t[j++]) && (h = "");
}
o.value = o.maxLength > -1 && o.maxLength < (t = t.join("")).length ? t.slice(0, o.maxLength) : t;
if(ob.c && ob.c != 46 && ob.c != 8){
if(si != lt){
while(m[si] != "#" && m[si]) si++;
ini && m[0] != "#" && si++;
}
else si = o.value.length;
}
!moz ? (obj.move("character", si), obj.select()) : o.setSelectionRange(si, si);
}

//***************************

?>

<html>
<head>
<title>Cadastro de Contratos</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>


<body>
<form action="inserir_contratos.php" method="post" name="cadcon" id="cadcon">
<center>
<table width="74%" border="1" cellspacing="0" cellpadding="3">
<tr>

<td>
<center>
<p> </p>
<table width="90%" border="0" cellspacing="0" cellpadding="3">
<tr bgcolor="#009966">
<td colspan="2"><div align="center"><strong><font color="#FFFFFF">CADASTRO
DE CONTRATOS</font></strong></div></td>
</tr>

<tr>
<td width="262"><div align="right">Base de Preços:</div></td>
<td width="455"><input name="a" type="text" id="a" size="20" maxlenght=20></td>
</tr>
<tr>
<td width="262"><div align="right">Data Assinatura:</div></td>
<td width="455"><input name="b" type="text" id="b" size="20" maxlenght=20></td>
</tr>

<tr>
<td width="262"><div align="right">Observações:</div></td>
<td width="455"><textarea name="c" cols="70" rows="5"></textarea></td>

</tr>
<tr>
<td colspan="2"><div align="right"><input type="submit" name="Cadastrar Contrato" value="Cadastrar"></div></td>
</tr>
</table>
</center>
<p> </p></td>

</tr>
</table>
</center>
</form>

<script type="text/javascript">
//<![CDATA[

var r = new Restrict("cadcon");
r.field.a = "\\d/";
r.mask.a = "##/##/####";
r.field.b = "\\d/";
r.mask.b = "##/##/####";
r.field.c = "a\\^bc";
r.onKeyRefuse = function(o, k){
o.style.backgroundColor = "#fdc";
}
r.onKeyAccept = function(o, k){
if(k > 30)
o.style.backgroundColor = "transparent";
}
r.start();

//]]>
</script>

</body>
</HTML>

#30 Davi Villalva Martins

Davi Villalva Martins
  • Visitantes

Posted 08/07/2006, 21:12

gostei do código super útil meu!




0 user(s) are reading this topic

0 membro(s), 0 visitante(s) e 0 membros anônimo(s)

IPB Skin By Virteq