Search code examples
vb.nettextboxintegervalidationmaxlength

VB.NET textbox maxlength for positive/negative integers


The problem is simple: I have a form with textboxes, and in one of those textboxes, I want users to enter either a positive or negative 2-digit number. I'm looking for an easy way to enforce this restriction, i.e. without having to parse the number and check whether its absolute value is below 100.

If I set the textbox maxlength to 2, they cannot enter numbers below -9. If the maxlength is 3, they can enter numbers above 99.

A masked textbox has no solution, I cannot make the "-" literal optional, or at least not that I know of.

What would be the simplest solution to this restriction: "An empty textbox will accept 2 input characters if no "-" is typed, otherwise it accepts 3"? Handling the change event to see if a "-" was typed and resetting maxlength seems a bit overkill...


Solution

  • You actually want a NumericUpDownControl. Use that, and set its Minimum and Maximum properties. No validation code required at all, and easily solves your problem.

    If you're stuck on using a TextBox then in short you're not going to get the desired functionality you want without actually checking the number. You could write a UserControl to do this and you could reuse it, but you still have to write some validation code.

    Just validate the integer using ASP.NET/Javascript style validation. This example uses a label with a ForeColor of Red to display validation messages.

    private void numberTextBox_TextChanged(object sender, EventArgs e) {
        int number;
    
        bool isValid = int.TryParse(numberTextBox.Text, out number);
    
        if (!isValid) {
            validationLabel.Text = "Must be a two-digit number.";
            validationLabel.Visible = true;
            return;
        }
    
        if (number < -99 || number > 99) {
            validationLabel.Text = "Must be between -99 and 99";
            validationLabel.Visible = true;
            return;
        }
    
        if (isValid) {
            validationLabel.Visible = false;
            // Do something else with your number
            // if you need to.
        }
    }
    

    There's nothing wrong with having to write code to do validation. You probably won't achieve good results using existing designer properties otherwise.