validate telephone numbers in c #

1

Good, how can I validate phone numbers in c# but that it only recognizes numbers and () - in its respective format? I have the following code to validate number but not for the above.

if (Char.IsNumber(e.KeyChar))//Si es número
   {
      e.Handled = false;
   }
   else if (e.KeyChar == (char)Keys.Back)//si es tecla borrar
   {
      e.Handled = false;
   }
   else //Si es otra tecla cancelamos
   {
      e.Handled = true;
   }
    
asked by Josue Martinez 31.10.2016 в 18:45
source

3 answers

3

Good morning, one option is to only accept numbers and when you save it, format it as follows:

string telefono = String.Format("{0:(###) ###-####}", 8005551212);

To know more about formats that you can give to a string you have this page

Another option is to use MaskedTextBox , to which you assign the format you want your entry to be in the Mask property, here you will find information on how to add a mask. Here is the example of how to add a mask to a phone

MaskedTextBox mascara = new MaskedTextBox();
mascara.Mask = "(999)-000-0000";

This is a Windows Forms control, so from the desingner you can put the mask.

If you are on the Web, I recommend you do it through JavaScript, here is a example .

The last option is to use Regex, I found an expression that works according to this post .

"/\(?([0-9]{3})\)?([ .-]?)([0-9]{3})([0-9]{4})/"
    
answered by 01.11.2016 / 00:00
source
1

Complementing the answer of @ randall-sandoval, if you do not want to use MaskedTextBox , you can use a method with the Regex pattern that suits you best and send it to call in the Leave event of a TextBox :

// Static class Utilerias

    public static bool ValidarTelefonos7a10Digitos(string strNumber)
    {
        Regex regex = new Regex("\A[0-9]{7,10}\z");
        Match match = regex.Match(strNumber);

        if (match.Success)
            return true;
        else
            return false;
    }

... // Leave Event of TelefonoTextBox

  if (Utilerias.ValidarTelefonos7a10Digitos(TelefonoTextBox.Text))
  {
          errorProvider2.SetError(TelefonoTextBox, "Debe capturar un teléfono de 7 a 10 digitos.");      
  }
    
answered by 01.11.2016 в 18:41
0

With the next event in the Text box

private void TextBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (!(char.IsNumber(e.KeyChar)) && (e.KeyChar != (char)Keys.Back))
{
  MessageBox.Show("Solo se permiten numeros", "Advertencia",   MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
  e.Handled = true;
  return;
 }
 }
    
answered by 31.10.2016 в 18:55