Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# entry validation regex

Tags:

c#

regex

winforms

I just started learning C#. Sorry for the noob question.

My first training app is one where you enter your age and output it in a message box.

I want to validate input with Regex so that entering letters makes it raise an error.

The problem is I can't make it accept the Regex.

        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            string age;
            age = textBox1.Text;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string regexpattern;
            regexpattern = "^\t+";
            string regex1;

            regex1 = Regex.IsMatch(regexpattern);

            if (textBox1.Text == regex1)
            {             
                MessageBox.Show("error, numbers only please!");
            }         
            else
            {
                string age;
                string afe;
                string afwe2;

                afe = "You are ";
                age = textBox1.Text;
                afwe2 = " years old!";

                MessageBox.Show(afe + age + afwe2);
            }
        }

Thanks!

like image 383
Zbone Avatar asked Apr 26 '26 19:04

Zbone


1 Answers

Your regex has to be

regexpattern = "^\d+$"; 

Edit And the coding is wrong. It has to be like that:

var regex = new Regex(@"^\d+$");

if (!regex.IsMatch(textBox1.Text))
{
    MessageBox.Show("error, numbers only please!");
}
like image 128
Fischermaen Avatar answered Apr 29 '26 10:04

Fischermaen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!