Format 001-000001 in a textbox (editbox)

2

I want to enter data into a text box the app is windows forms, what I want to enter is in this format 001-000001 the first two digits are zero the third digit of 1 to 9 the fourth digit a - of the fifth digit to the tenth of 0 to 9 , how could you do it?

private void txtGuiaRemision_KeyPress(object sender, KeyPressEventArgs e)
    {
        string valor = txtGuiaRemision.Text;
        string re1 = "(\d+)";
        string re2 = "([-+]\d+)";

        Regex r = new Regex(re1 + re2, RegexOptions.IgnoreCase | RegexOptions.Singleline);
        Match m = r.Match(valor);
        if (m.Success)
        {
            String int1 = m.Groups[1].ToString();
            String signed_int1 = m.Groups[2].ToString();
        }
    }

I can not do what I want.

    
asked by Pedro Ávila 27.07.2016 в 03:13
source

2 answers

3

It would not be simpler if you use the control MaskedTextBox you could define the Mask of the control with this format that you mention

MaskedTextBox in C #

Also if you apply a regular expression you should not implement it in the keypress, but you would in the Validating, the regular expression applies when you want to leave the textbox, that is when you enter all the content

How to: Display Error Icons for Form Validation with the Windows Forms ErrorProvider Component

    
answered by 27.07.2016 / 03:45
source
2

Complementing the response from @Leandro , if you wanted to use regex to validate that format, it would be:

^00[1-9]-[0-9]{6}$
  • ^ matches the beginning of the text
  • 00 with literal "00"
  • [1-9] with 1 digit other than "0"
  • - with 1 dash
  • [0-9]{6} with 1 digit, repeated 6 times
  • $ with the end of the text


Code

string valor = "001-000001";
Regex re = new Regex(@"^00[1-9]-[0-9]{6}$");

if (re.IsMatch(valor)) {
    Console.WriteLine("Válido");
} 
else
{
    Console.WriteLine("Error");
}

ideone.com demo

    
answered by 27.07.2016 в 05:27