Validate content from Textbox

Asked

Viewed 7,370 times

0

I have the fields TextBox, for example:

  • txtValorCompra would have to be typed by the user 98,90 and it can’t be letters
  • txtNumero integer input
  • nome only letters.

You’d be able to do that on the form?

  • 1

    You can use another control that allows you to use a mask (Maskedtextbox). Or use the control events to manually validate what was entered during or at the end of typing.

  • Something to read: http://www.codeproject.com/Articles/220519/Numbers-or-Characters-only-Textbox-Validation-in-C, http://stackoverflow.com/questions/15399323/validating-whether-a-textbox-contains-only-numbers,

4 answers

3

personal I did something that worked I will 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;
        }

1

In my project, I had the need to develop various controls to meet specific needs and one of them was precisely the issue above. I developed a Usercontrol that only accepted numbers. The component followed the reference in the link below: http://www.vcskicks.com/numbers_only_textbox.php

1

I had to do this on a recent project.

What I did was use the event Leave of 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();
    }
}

0

Can use a MaskedTextBox for what you want. The property Mask allows you to define which are the inputs accepted.

In your case the Mask would be:

  • txtValorCompra (98,90) => 00,00 (Required to enter 4 numbers, a MaskedTextBox automatically places the decimal separator);

  • txtNumer => 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 entered text:

aminhamaskedTextBox.ValidateText();

If you need to display a message to the user when the input entered and invalidated, can use the event aminhamaskedTextBox_MaskInputRejected(object sender, MaskInputRejectedEventArgs e).

Browser other questions tagged

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