Search code examples
c#-4.0street-addressmaskedtextbox

Zip code size test C#


I have a small piece of code that I have been trying to get to work, but nope. So I've come to the experts. I'm trying to test a zip code entry and limit it to 5 digits only. My first issue is with the attached code. It doesn't seem to be counting the length properly. Also, how can I limit the user so if they try to type a 6th character, it won't show or be accepted?

private void textBoxZip_TextChanged(object sender, EventArgs e)
    {
        String userInputString;
        int length,
            max = 5;

        userInputString = textBoxZip.Text;
        numberTest(userInputString);

        length = userInputString.Length;
        if (length > max)
        {
            labelErrorMessage.Text = "Maximum length 5 numbers";
        }
    }

Solution

  • I think using a MaskedTextBox would be an easy solution. This will allow you to easily accept only a certain # of characters in a specified format.

    The MaskedTextBox is a standard .NET control in the control toolbar in Visual Studio.