Click here to Skip to main content
15,885,278 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am trying to validate textbox in windows form app, The match should be like - first digit 1,2,or 3, second digit 1 or 2,third also 1 or 2

What I have tried:

regular expression @"^[1-3]{1}[1-2]{1}[1-2]{1}$"

But it not work...any suggestions..
Posted
Updated 28-Aug-19 19:54pm
v2
Comments
Mohibur Rashid 28-Aug-19 22:22pm    
your regex seems ok. But how about your c# code?
Patrice T 28-Aug-19 23:02pm    
Describe 'not work' and show code using the regex.

1 solution

You can simplify the regex to just
^[123][12]{2}$
and it will work the same, but your original should work fine.
So it has to be your C# code.
Try this:
C#
private void MyTextBox_Validating(object sender, CancelEventArgs e)
    {
    if (sender is TextBox tb)
        {
        if (Regex.Match(tb.Text, "^[123][12]{2}$").Success)
            {
            // Validated OK
            e.Cancel = false;
            }
        else
            {
            // validation failed
            e.Cancel = true;
            }
        }
    }
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900