Thursday, May 5, 2011

C# Input validation for a Textbox: float

This supposedly easy task gave me some headache. I simply want to let the user enter any text that succeeds float.TryParse into a Textboxish control.

I could use a normal TextBox and check the Text in some btnOK_Click, but this is obviously lame. Also, there is a nice built-in MaskedTextBox control, but I failed to set it's mask to be equal to float.TryParse. Also, it seems to check for validity only when a focus change occurs.

Digging around on the net brought some interesting ideas, but none of them as nice as I would like.

How did you solve this problem? Did I simply miss an obvious solution, or do I have to implement this functionality myself?

I'm aware of a few similar threads on SO, but there was no feasible solution to be found.

Update: Yes, WinForms.

From stackoverflow
  • Edit

    Well that makes it alot easier... Just add a Validating Event Handler to your textbox and do the TryParse in the code behind. If its invalid, prompt the user as such.

    Validating will fire when the user is finished typing and moves focus from the TextBox so if you need to do on the fly checking, you could handle the TextChanged or on of the KeyPress/KeyUp Event handlers instead


    Is this in or winforms/wpf

    If its, you could use a combination of RegularExpressionValidator (to account for comma seperation, 1 decimal point, etc...) and a RangeValidator to set the min/max values for a float.

    Aside from that, the only way to guarantee it would be to wrap the textbox in an updatepanel, stick a CustomServerValidator on it, and in the server validate function, do a TryParse on the TextBox.Text value, if it succeeds, IS VALID, if it fails, NOT VALID

  • Be careful using Validating and validating to false. You might find that, unless you enter valid data, you can't move focus off the textbox which is a really big usability pain.

    I solve this by simply trying a TryParse() on LostFocus and if the TryParse fails I color the textbox background a reddish tint to make it obvious that something is wrong.

    mafutrct : In my final solution I'm caching the last valid value and, if needed, reset the text if the focus is lost.
    mafutrct : Your idea to change color was nice. In my solution, coloring immediately on invalid values makes it obvious to the user that he should change the value.


Post a Comment