Using Keypress event with Regex

Asked

Viewed 376 times

2

I’m making an application C# in Windows Form using .Net Framework 3.5. In this application I have a textbox for the input of CPF or CNPJ.

I need this field to have only CPF/CNPJ numbers and characters (./-). I would like to validate this field in the event Keypress using Regex. Would it be possible?

1 answer

2

Instead of validating the textbox in the KeyPress, do in the Validating. This avoids the use of Regex with each button pressed.

private void textBox_Validating(object sender, CancelEventArgs e)
{
    // Corra o regex aqui. Caso não seja o que pertende, cancele o evento.
    e.Cancel = true; // Cancela o evento e impede o utilizador de sair da textbox
}

When cancelling the event, the user is prevented from taking the focus of the textbox and can bring up a tooltip or change the color of textbox to indicate that there is an error with the value entered.

  • Omni, I need it to be every key pressed, so I need it to be the Keypress event.

  • @andreguilherme can I ask why it has to be every key press? Ever thought about using a Maskedtextbox?

  • Boss wants it that way :(

  • @andreguilherme it is not for me to opine on the decisions made without knowing the reasons. Anyway can validate the field in the same KeyPress, but it will not prevent the user from leaving the field for example (at least without additional logic). And as I mentioned, running a regex every key costs. Just a detail that is not clear in your question, also wants to know how to do the Regex?

Browser other questions tagged

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