Validate Textbox

0

I need to validate some textbox in C# so that only whole numbers are entered, with an exact number of digits, that is, I can enter figures of 5 numbers and not greater than this number of characters.

How could I do this validation?

    
asked by Alberto Arenas 04.01.2017 в 03:08
source

4 answers

2

You can do it using another control called "MaskedTextBox".

This link will give you a good idea of how to use it: link

    
answered by 04.01.2017 в 03:28
1

Create a method that receives a textbox as a parameter, as follows

    public boolean validatxtLongitud(TextBox txttoValidate)
        {
try
{
         if(txttoValidate.Text().Lengh=5 && (int)txttovalidate.text()!=0)
          {
           return true;
          }
          else
          {
           return false;
          }
}
catch(Exception e)
{
throw e;
return false;
}
        }

And where you use it, do this

if(validatxtLongitud(txtinput))
{
// haz algo
}
else
{
//haz otra cosa
}
    
answered by 04.01.2017 в 04:02
0

You can use the events, it's quite practical and I think it saves you a lot of code.
The event is KeyPress

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (Char.IsPunctuation(e.KeyChar)) //Comparas si la tecla presionada corresponde a un signo de puntuacion
        {
            e.Handled = true; //Si coincide se controla el evento, es decir, no se escribe el caracter
        }
        if (Char.IsSymbol(e.KeyChar)) //Comparas si la tecla presionada corresponde a un simbolo
        {
            e.Handled = true;
        }
        if (Char.IsLetter(e.KeyChar)) //Comparas si la tecla presionada corresponde a una letra
        {
            e.Handled = true;
        }
    }

The previous code is used to replace the validations that are made comparing the content of TextBox , since only numbers can be written.

And as for the length of TextBox there are two ways, one is visually modifying the property MaxLength and assigning the desired value, in your case 5.

Or the other one is by code:

textBox1.MaxLength = 5; //Si es en WF puedes hacer la declaracion en el metodo Form_Load

If it worked for you, do not forget to mark it!

    
answered by 28.07.2018 в 18:06
0

In my opinion the most efficient way was through a regular expression, then I give you an example

        if(Regex.IsMatch(txtbox, @"^\d{5}$")){

         //EN CASO CORRECTO

        }else{

       //EN CASO DE ERROR

       }
    
answered by 07.11.2018 в 21:08