CPF mask in the textBox?

2

I'm using the following code:

string numero = "";
private void MaskeditCPF(TextBox txt, KeyEventArgs e)
{
    //Verifica de a tecla digitada foi algo diferente de números ou BackSpace
    if (e.Key != Key.Back && (e.Key < Key.D0 || e.Key > Key.D9))
    {
        e.Handled = true;
    }
    else
    {
        if (e.Key == Key.Back && numero.Length > 0) //Se digitou BackSpace então retiramos o último número digitado
            numero = numero.Substring(0, numero.Length - 1);
        else
            numero += Convert.ToChar(e.PlatformKeyCode).ToString(); //Concatenamos o número digitado aos já existentes

        //Verificações para realizar o maskedit em C#. Nesse caso o formato são números com 2 casas decimais
        if (numero.Length == 0)
            txt.Text = "";
        else if (numero.Length < 2)
            txt.Text = "0-0" + numero;
        else if (numero.Length == 2)
            txt.Text = "0-" + numero;
        else
            txt.Text = numero.Substring(0, numero.Length - 2) + "-" + numero.Substring(numero.Length - 2, 2);
    }
}

private void cpf_KeyDown(object sender, KeyEventArgs e)
{
    MaskeditCPF(cpf, e);
}

I found it on a blog and changed it, but I do not know how to make it into a CPF mask, just like it's textBox is: 123456789-01 how do I get 123.456.789-01 ?

    
asked by anonymous 12.07.2015 / 17:22

2 answers

4

You will have to use the String.Format. In your case, you just need to grab the contents of your TextBox and change the format:

long CPF = Convert.ToInt64(txt.Text);
string CPFFormatado = String.Format(@"{0:
long CPF = Convert.ToInt64(txt.Text);
string CPFFormatado = String.Format(@"{0:%pre%0\.000\.000\-00}", CPF);
txt.Text = CPFFormatado;
0\.000\.000\-00}", CPF); txt.Text = CPFFormatado;
    
28.09.2015 / 12:37
2

Do the customer side would not be better? Here is a suggestion using javascript with jQuery.

These would be your includes:

<script type="text/javascript" src="js/jquery-1.2.6.pack.js"></script>
<script type="text/javascript" src="js/jquery.maskedinput-1.1.4.pack.js"/></script>

Here we have the jquery itself:

<script type="text/javascript">
    $(document).ready(function() {
        $("#cpf").mask("999.999.999-99");
    });
</script>

And here's the call on form:

<form name="form" method="post" action="">
    <input name="cpf" type="text" id="cpf"/>
</form>

Of course all this will require an adaptation to your programmatic reality.

    
13.07.2015 / 01:41