JavaScript: formatar data

Written by oraculum. Posted in .NET, Django, Frameworks / DBAs | Tagged: , , , , , ,

JavaScript: formatar data

Published on Julho 12, 2009 with Sem Comentários

Segue-se um script muito útil que vem me ajudando muito, uso ele para formatar data, cpf, cep e seja lá o que você preferir, bem como ele é bem dinâmico da pra fazer bastante coisa:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<script language="JavaScript" type="text/JavaScript">
function formatar(src, mask)
{
 
    // permitindo alguns caracteres importantes
    switch(event.keyCode)
    {
        case 8:     // backspace
        case 9:     // tab
        case 37:    // left arrow
        case 39:    // right arrow
        case 46:    // delete
        event.returnValue = true;
        return;
    }
 
    var i = src.value.length;
    var saida = mask.substring(0,1);
    var texto = mask.substring(i)
    if (texto.substring(0,1) != saida)
    {
        src.value += texto.substring(0,1);
    }
}
</script>

Nos controles você faz assim:

<asp:TextBox ID="txtDataIN" OnKeyPress="formatar(this, '##/##/####')" runat="server" TextMode="SingleLine" Columns="10" CssClass="inputbox" MaxLength="10" Width="80px"></asp:TextBox>

o que vale ali é essa parte: OnKeyPress=”formatar(this, ‘##/##/####’)” aqui é simples se você quiser uma formatação de:

CPF -> OnKeyPress=”formatar(this, ‘###.###.###-##’)”
CEP -> OnKeyPress=”formatar(this, ‘###.###-###’)”

Entenderam é só ir organizando os # no lugar dos números o resto você deixa por conta do script

Acerca oraculum

Browse Archived Articles by oraculum

Sem Comentários

There are currently no comments on JavaScript: formatar data. Perhaps you would like to add one of your own?

Leave a Comment