MaskedTextBox for ID number with leading zeros

1.1k Views Asked by At

I've created a WinForm that has a field for an employee or student ID number. All ID numbers are 9 digits long with 2 leading zeroes (ex. 001234567). How can I configure the text mask to validate the user's input and require leading zeros but prevent input being all zeros? I can make this happen with a regular text box, but changed to a MaskedTextBox to prevent special characters like the Windows Emoji keyboard emojis as input.

2

There are 2 best solutions below

1
Anu Viswan On

You could set the mask as following

\0\00000000

This would ensure you have two leading zero literals before the remaining 7 digits

0
Jack J Jun On

You can use the following code to make sure the leader is "00" and stop the input from

being zeros.

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }



    private void Form1_Load(object sender, EventArgs e)
    {
        maskedTextBox1.Mask = "00/0000000";

        maskedTextBox1.MaskInputRejected += new MaskInputRejectedEventHandler(maskedTextBox1_MaskInputRejected);
    }
    void maskedTextBox1_MaskInputRejected(object sender, MaskInputRejectedEventArgs e)
    {
         if (!maskedTextBox1.Text.StartsWith("00")) 
        {
            MessageBox.Show("You must input start with 00");
        }
        else if (maskedTextBox1.Text == "00/0000000") 
        {
            MessageBox.Show("You can not input all number is 0");//
        }
        else if (maskedTextBox1.MaskFull)   
        {
             MessageBox.Show("You cannot enter any more data into the date field. Delete some characters in order to insert more data.");
        }
    }
}

Test Result:

enter image description here