C# Input validation for a Textbox: float

mafu picture mafu · May 6, 2009 · Viewed 17.8k times · Source

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.

Answer

Eoin Campbell picture Eoin Campbell · May 6, 2009

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

Original

Is this in asp.net or winforms/wpf

If its asp.net, 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