CPF mask in the textbox?

Asked

Viewed 9,037 times

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, but I do not know how to turn it into CPF mask, just as it is the textbox gets: 123456789-01 how do I get 123.456.789-01?

2 answers

4


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

long CPF = Convert.ToInt64(txt.Text);
string CPFFormatado = String.Format(@"{0:\000\.000\.000\-00}", CPF);
txt.Text = CPFFormatado;

2

Wouldn’t the client side be better? Here’s a suggestion using javascript with jQuery.

Those 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 jquery itself:

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

And here’s the call on the 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.

  • I don’t know anything about Windows Fone, but Jquery works on it?

  • He’s working on windows-phone in c# isn’t that right? I don’t think javascript-jquery would apply to that.

  • Jquery works, but in another type of application, Javascript applications (which do not have as many features as C#applications), here’s the problem, C# for Windows Phone has no method for masking, the code I used was created from scratch to serve as a mask. But I got lost when it came to putting the stitches in the mask, because it’s a handwritten calculation with the .Length

  • 1

    I’m sorry, I didn’t see it was Wphone.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.