Using KeyPress event with Regex

2

I'm doing a C # application on Windows Form using .Net Framework 3.5 . In this application I have a textbox for the entry of CPF or CNPJ.

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

    
asked by anonymous 10.06.2014 / 20:47

1 answer

2

Instead of validating textbox in KeyPress , do in Validating . This avoids using Regex for each key 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 canceling the event, the user is prevented from taking focus from the textbox and can make a tooltip appear or change the color from textbox to indicate that there is an error with the entered value.

    
10.06.2014 / 20:57