Home > Software design >  C# .Net How to auto separate Textbox input with comma
C# .Net How to auto separate Textbox input with comma

Time:09-26

I want to allow the following sequence on my textbox.

e.g. 
    09123456789
e.g.
    09123456789,09123456789
e.g.
    09123456789,09123456789,09506724016

The input should start with 09 followed by the next nine numbers. If more than eleven is input, then a comma should automatically add at the end then it should start again with 09 followed by the next nine numbers.

I have this regex ^(09)\\d{9} that accepts only the first sequence, but I don't how to apply the whole sequence into my Textbox.

private void phone_number_TextChanged(object sender, EventArgs e) {
   //validate the textbot to allow only the sequence.
}

CodePudding user response:

Your regex accepts only the first sequence because it contains a start-of-input character ^. If you want to detect that it's time to add a comma use 09\\d{9}$ instead. Maybe you could prefill the 09 for the user too

If you want to also do something like turn the back color red if the entry isn't a match, consider checking that the textbox complied with logic like:

private Regex _phNum = new Regex(@"^09\d{9}$", RegexOptions.Compiled);

And then a text changed like:

tb.BackColor = tb.Text.Split(',').All(_phNum.IsMatch) ? Color.White : Color.Red;
  • Related