'Validate 5 digits in the textbox

I am trying to make the textbox valid when just the user writes 5 digits but the problem is if I for example input (11111) it will be correct, the program will not show an error message. But if the id was for example (12345) the message box will show how I can solve it?

namespace black_clover_project2
{
    public partial class Add_student : Form
    {
        public Add_student()
        {
            InitializeComponent();
        }

        private void label4_Click(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
            
            student s = new student();
            Regex regex = new Regex(@"^[0-4]{5}$");
            if (regex.IsMatch(s.id = tbid.Text))
            {
                s.id = tbid.Text;
            }
            else { MessageBox.Show("invalid id"); } // 5 dig condtion for id
           
            if (String.IsNullOrEmpty(tbname.Text))
            {
                MessageBox.Show("please write the first name");
            }
            else  { s.name = tbname.Text; } // name condtion 

            s.lastname = tblastname.Text;
            s.email= tbemail.Text;
            s.dob = tbdob.Text;
            s.dos = tbdos.Text;
        }

        private void button3_Click(object sender, EventArgs e)
        {
            Form1 f1 = new Form1();
            this.Hide();
            f1.ShowDialog();
            this.Close();
        }

        private void tbid_TextChanged(object sender, EventArgs e)
        {

        }
    }
}


Solution 1:[1]

The issue is with your if statement:

if (regex.IsMatch(s.id = tbid.Text))
{
    s.id = tbid.Text;
}

Change to

if (regex.IsMatch(tbid.Text))
{
    s.id = tbid.Text;
}

You need to check the input against the regex condition, and then if it is valid, pass the value to object id.

Solution 2:[2]

You don't need to use regex. To verify you can test if the length of the string if equal to 5 and then test if it is an integer. Also in my opinion you should be checking as the user types and not after he is finished so that if there are 5 digits entered then an "OK" or "DoSomething" button is enabled.

private void OnTextChanged(object sender, EventArgs e)
    {
        bool isOK = false;
        if (textbox1.Text.Length == 5)
        {
            int i = 0;
            if (Int32.TryParse(textbox1.Text, out i))
                isOK = true;
        }
        button1.Enabled = isOK; 
    }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 MtnManChris