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.
Asked
Active
Viewed 1,000 times
-1

ProgrammingLlama
- 36,677
- 7
- 67
- 86

jpollock0010
- 3
- 3
-
Use [int.TryParse](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/strings/how-to-determine-whether-a-string-represents-a-numeric-value) to validate that they entered a positive integer. And if it were me, I'd add the leading zeros for them if the number was valid otherwise. – ourmandave Feb 21 '20 at 03:12
-
@ourmandave I'm not sure if I was doing it wrong, but using int.TryParse to check for a positive integer has the same problem of allowing a value of all zeros (ex. 000000000). I need to keep users from entering all zeros. – jpollock0010 Feb 21 '20 at 03:38
-
If they enter all zeros, TryParse will return True, but you can test that the 'out' value is >0. – ourmandave Feb 21 '20 at 12:55
2 Answers
0
You could set the mask as following
\0\00000000
This would ensure you have two leading zero literals before the remaining 7 digits

Anu Viswan
- 17,797
- 2
- 22
- 51
-
It looks like this does give me the leading zeros I need, but it doesn't stop the input from being all zeros. This is the code I currently have, with your suggestion as the mask: `if (this.Text == "000000000" || (string.IsNullOrWhiteSpace(this.Text))) { MessageBox.Show("This field does not contain a valid Student or Employee ID number. Please try again.", "Whoops!", MessageBoxButtons.OK, MessageBoxIcon.Error); }` – jpollock0010 Feb 21 '20 at 02:45
0
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:

Jack J Jun
- 5,633
- 1
- 9
- 27