Validate TextBox content

0

I have the TextBox fields, for example:

  • txtValorCompra would have to be typed by user 98,90 and can not be letters
  • txtNumero entry with integers
  • % with only letters.

Would you like to do this on the form?

    
asked by anonymous 03.11.2014 / 22:44

4 answers

3

Personal I did something that worked out well I'll post here to help other users

        //não permitir augumas coisas 
        if (char.IsLetter(e.KeyChar) || //Letras

            char.IsSymbol(e.KeyChar) || //Símbolos

            char.IsWhiteSpace(e.KeyChar)) //Espaço

            e.Handled = true; //Não permitir

        //só permitir digitar uma vez a virgula
        if (e.KeyChar == ','
            && (sender as TextBox).Text.IndexOf(',') > -1)
        {
            e.Handled = true;
        }
    
04.11.2014 / 23:27
1

In my project, I had the need to develop various controls to meet specific needs and one of them was just the above question. I developed a UserControl that only accepted numbers. The component followed the reference present in the link below: link

    
04.11.2014 / 18:35
1

I needed to do this in a recent project.

What I did was to use the Leave event of the TextBox to validate the data using REGEX.

public const string EXPRESSAO = @"^\d+(\,\d{1,2})?$"; //Expressão para validar decimais

private void TextBox_Leave(object sender, EventArgs e)
{
    var tb = sender as TextBox;

    var valido = System.Text.RegularExpressions.Regex.IsMatch(tb.Text.Trim(), EXPRESSAO);

    if (!valido)
    {
        MessageBox.Show("Valor inválido!");
        tb.Focus();
    }
}
    
04.11.2014 / 18:52
0

You can use a MaskedTextBox for what you want. The Mask allows you to define what the inputs are accepted.

In your case the Mask would be:

  • txtValueBuy (98.90) = > 00.00 (Required to enter 4 numbers,% with% automatically places the decimal separator);

  • txtNumber = > 0000 (Required to enter 4 numbers);

  • name only letters = > LLLL (Required to enter 4 characters);

There are more combinations that you can use.

Finally in your code, to validate and use the text entered:

aminhamaskedTextBox.ValidateText();

If you need to display a message to the user when input is entered and invalid, you can use the MaskedTextBox event.

    
04.11.2014 / 19:10