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…
You actually want a
NumericUpDownControl. Use that, and set itsMinimumandMaximumproperties. No validation code required at all, and easily solves your problem.If you’re stuck on using a
TextBoxthen in short you’re not going to get the desired functionality you want without actually checking the number. You could write aUserControlto 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
ForeColorof Red to display validation messages.There’s nothing wrong with having to write code to do validation. You probably won’t achieve good results using existing designer properties otherwise.