473,569 Members | 2,562 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

A function to only allow numeric input in a textbox

mshmyob
904 Recognized Expert Contributor
Here is a way to limit user input in a textbox to only numeric characters.

I have created a function and I put mine in a Class module that holds my custom functions. The function is called from the KEYPRESS event of any textbox control where you want to limit to numeric input.

The only parameter you may wish to change is the last parameter which determines the number of digits to the right of the decimal place. This sample code limits the input to 2 decimal places.

Code for KEYPRESS event

Expand|Select|Wrap|Line Numbers
  1. Dim myTextBox As TextBox
  2. myTextBox = Me.ActiveControl
  3. If myMiscClass.myNumOnly(e.KeyChar, Me.ActiveControl.Text, myTextBox.SelectionStart, 2) = True Then
  4.         e.Handled = True
  5. Else
  6.         e.Handled = False
  7.  End If
  8. If e.KeyChar = Chr(13) Then GetNextControl(Me.ActiveControl, True).Focus() 'Enter key moves to next control
  9.  
Code for Function (I put this in it's own class module (so I only need it once) but you may put it in your form module if you wish.)

Expand|Select|Wrap|Line Numbers
  1. '*****************************************************
  2. ' myNumOnly()
  3. ' Purpose: Limits textbox input to numeric only
  4. ' Inputs:   strKeyPress, key pressed
  5. '           strText, current text in textbox
  6. '           intPosition, current cursor position in textbox
  7. '           intDecimal, number of decimal places required
  8. '       ' Returns: False/True - discard keystroke/valid key
  9. '*****************************************************
  10. Shared Function myNumOnly(ByVal strKeyPress As String, ByVal strText As String, ByVal intPosition As Integer, ByVal intDecimal As Integer) As Boolean
  11.  
  12. Dim dot As Integer, ch As String
  13.  
  14. If Not Char.IsDigit(strKeyPress) Then myNumOnly = True
  15. If strKeyPress = "-" And intPosition = 0 Then myNumOnly = False 'allow negative number
  16. If strKeyPress = "." And strText.IndexOf(".") = -1 Then myNumOnly = False 'allow single decimal point
  17. dot = strText.IndexOf(".")
  18. If dot > -1 Then 'limit to set decimal places
  19.        ch = strText.Substring(dot + 1)
  20.        If ch.Length > (intDecimal - 1) Then myNumOnly = True
  21. End If
  22. If strKeyPress = Chr(8) Then myNumOnly = False 'allow Backspace
  23. Return myNumOnly
  24. End Function
  25.  
Feel free to ask any questions.

cheers,
Mar 10 '10 #1
1 11797
yarbrough40
320 Contributor
Thanks for this! I have written it in a notepad for posterity.
Mar 11 '10 #2

Sign in to post your reply or Sign up for a free account.

Similar topics

9
4940
by: Penn Markham | last post by:
Hello all, I am writing a script where I need to use the system() function to call htpasswd. I can do this just fine on the command line...works great (see attached file, test.php). When my webserver runs that part of the script (see attached file, snippet.php), though, it doesn't go through. I don't get an error message or...
9
10419
by: Rowan Chapman | last post by:
Hey all! I'm kinda new to VB but not to programin'. So I know what it is like when you are asked trivial questions. Could some1 please tell me what the syntax would be 2 only allow numerical data into a textbox. thankz in advanced -Ro -------------------------------------------------------------------- " Reality is an illusion caused by...
3
8639
by: Craig | last post by:
I currently have the following code: <input name="castStation" type="text" value="0" onChange="valueCalculate()";> The function called does a few caluclations and writes the total to a total box. However, if the user type a non-numeric char, I get NaN.
1
4634
by: Jose Gonzalez | last post by:
How to apply a numeric format to a textbox using xhtml? I know you have to use the "-wap-input-format" style tag in css. I can get this to work in a regular xhtml page, however, I've been unsuccessful in getting it to work in asp.net 1.1 The following code has allowCustomAttributes set and works fine for labels, but not for textboxes. This...
2
5538
by: Sam | last post by:
Why isn't there a numberBox Windows Form control like a textbox control but for numeric (float) input? There doesn't seem to be any easy or visual solution to this VERY SIMPLE ISSUE in either version of Visual Studio. I simply wanted to create a Windows app where a user could enter miles or kilometers, gallons or liters, and see the other...
5
4666
by: MrMike | last post by:
Hi. I'm trying to create a simple validation process that only allows a user to enter a numeric value into a textbox. However, my process does not work and the user can still enter non-numeric values. My code is below. How can I fix this? Thanks. If Not (IsNumeric(CType(e.Item.Cells(3).Controls(0), TextBox).Text)) Then...
16
8341
by: Keith | last post by:
Am I crazy - to be shocked that there is no Numeric, Alpha, and AlphaNumeric Property in on the Textbox control I searched and searched - and found other people's code - but they don't work perfectly. Some do only allow numeric - but you cannot backspace. Maybe that is "good enough" - but surely it is not that difficult to have a textbox that...
4
6939
by: viv | last post by:
how do you trap keyboard codes for text box in VB2005 ? I'm looking for a code snippet to only allow numeric input in a text box (same as Key event in VB6, then use Keyascii to decide action) can anyone provide a snippet of code please many thanks
3
2460
by: shyamg | last post by:
hi all, This javascript is working IE but not working in FIreFox, validating text fields. var dealerid = new keybEdit('abcdefghijklmnopqurstuvwxyz01234567890 ','Alpha-numeric input only.'); var dealinit = new keybEdit('abcdefghijklmnopqurstuvwxyz01234567890 ','Alpha-numeric input only.'); var dealername = new...
3
3398
LoanB
by: LoanB | last post by:
Hi I'm looking to ensure that my textbox only accepts numbers .. AND ... mathematical operators + - . / *. an dmaybe a blank space I can ensure that only number are included by using: private void txtSurname_KeyPress(object sender, KeyPressEventArgs e) { if (e.Handled = !(Char.IsDigit(e.KeyChar))) {
0
7701
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7615
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
8130
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
0
7979
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
6284
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5514
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
3653
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3643
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
940
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.