Restrict entry to only decimals

DiverDan

Contributor
Joined
Jan 16, 2003
Messages
645
Location
Sacramento, CA
How do you restrict a textbox entry to only decimals and still have the backspace operational? Is there a way to leave the "0." beginning text in the textbox and then restict only number entry?

Thanks
 
I dont' think there's a built in way. divil has written a tutorial on creating an input masked text box (or something similar) yourself, if you search for 'input mask' on the forum. There's also a really nice sample app on MSDN where by they add a ValidationExpression (regex) to a textbox and an error message when it doesn't pass. It comes with examples for ssn, phone number, and email.
Generally,
http://msdn.microsoft.com/vbasic/downloads/samples/101samples.asp

Specifically,
http://msdn.microsoft.com/library/d...us/dnvssamp/html/vbcs_ValidatingTextboxes.asp

hope this helps. maybe someone knows an easier way but I really like the RegExTextBox.
 
Thanks quwiltw,

I've got the "after fact" validation covered pretty well. As Divil mentioned in his tutorial, popup messages are a bit annoying. I am searching for a method similar to number restriction in a textbox that allows only decimals or resticts the backspace from removing the "0." prefix in the textbox.

Thanks
 
All you need to do is see if the current text in the text box equals "0." and then ignore the backspace key if it is.

Am I missing something?
Visual Basic:
Private Sub txtInput_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtInput.KeyPress
    If txtInput.Text = "0." Then
        If e.KeyChar = Chr(Keys.Back) Then
            e.Handled = True
        End If
    End If
End Sub
 
Copy some non-conforming number from the clipboard, right-click->paste would probably break that. I still think the solution presented in the RegExValidation sample app works, just don't pop up a message and call Validate() on relevant events. Or extend Orbity's solution a bit further by handling all relevant events and changing it to be the left two characters = "0."
 
It seems you're right quwiltw. Eventhough I've prevented pasteing into the textbox, when the user tabs into the textbox, the "0." text is highlighted then overwritten with user entry. I have validation of the textbox's value via a button push and I am hoping to also restrict entry.

Thanks to you both,
Dan
 
Last edited:
Back
Top