Textbox validation, cursor skipping to the start of the text - vb.net

In vb.net, I have the following code to validate acceptable characters that can be entered into a textbox.
Private Sub txt_mobile_phone_TextChanged(sender As Object, e As EventArgs) Handles txt_mobile_phone.TextChanged
Dim s As String = ""
For Each C As Char In txt_mobile_phone.Text
If (C >= "0" And C <= "9") OrElse (C = " ") OrElse (C = "-") OrElse (C = "+") Then
s &= C
End If
Next
txt_mobile_phone.Text = s
End Sub
The problem is, is that when someone enters an invalid character (for example, an exclamation mark '!'), the cursor position then skips to the start of the text string, and all further characters are entered at the start.Is there a way to make it so that it ignores invalid characters and carries on typing from the end of the string?
If possible, without using txt_mobile_phone.SelectionStart = txt_mobile_phone.Text.Length -1 as this means that clicking the middle of the string to add to the middle of it will break (which currently is possible)

The issue is that you are firing an event on the TextChanged, that is int he middle of something. For your purpose, to validate entries, you have got the KeyPress event, whereby you have the e.Handle to block entries.
Find the example below, which I applied in my application to accept only numeric and should not accept spaces;
Private Sub txt_mobile_phone_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txt_mobile_phone.KeyPress, _
AcEmpNo.KeyPress
' Accept only numeric values
If (e.KeyChar < Chr(48) OrElse e.KeyChar > Chr(57)) _
AndAlso e.KeyChar <> Chr(8) Then
e.Handled = True
End If
End Sub
You can also use Char convertor if you don't know the code like;
e.KeyChar = ChrW(Keys.Space)
Hope this helps.

Related

Automatically remove not authorized character on Regular Expressions just after being typed

I'm using this code
Private Sub MyTextBox_KeyPress(sender As Object, e As KeyPressEventArgs) Handles MyTextBox.KeyPress
If Not Regex.Match(MyTextBox.Text, "^[a-z /s ']*$", RegexOptions.IgnoreCase).Success Then
MyTextBox.Text = MyTextBox.Text.Remove(MyTextBox.SelectionStart - 1, 1)
MyTextBox.Select(MyTextBox.Text.Count, 0)
End If
End Sub
so the user can only add letters, space and apostrophe
The code works if the user digit
somethin8g
the number 8 is removed
But if the user just digit
somethin8
the number 8 is visible until the user press another key, and even worst, if the user press the "SAVE" button the info is accepted even with the number 8
Is there a better way to automatically remove not authorized character on Regular Expressions just after being typed?
Generic solution adaptable to any situation (Just changing the allowedChars string)
No regular expression needed
Private Sub TextBox1_KeyPress(sender As Object, e As KeyPressEventArgs) _
Handles txtName.KeyPress
If Not (Asc(e.KeyChar) = 8) Then
Dim allowedChars As String = "abcdefghijklmnñopqrstuvwxyzáéíóúàèìòùäëïöüâêîôû '"
If Not allowedChars.Contains(e.KeyChar.ToString.ToLower) Then
e.KeyChar = ChrW(0)
e.Handled = True
End If
End If
End Sub
Adapted from the answer of Jhon Woo on Get a textbox to accept only characters in vb.net

How to check individual component in the Visual basic. Error checking

In the text box, I only want a 3 number combination of 0 and 1 as 011,110,111,001, etc. How can I write to check individual component(from three numbers) is 0 or 1, and specify this for checking error?
I want to have a if statement if possible.
For example,
If the number is 015, this message will be shown.
MsgBox("Please Insert a combination of 0,1 into the text box.")
I would simply restrict character entry to zeroes and ones as the user enters them, and limit the length. You'll have to adjust this code for the proper If checks; I'm a C# guy, not a VB guy.
Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
If e.KeyChar <> ChrW(Keys.Back) Then
If Textbox1.Length < 3 and (e.KeyChar = "0" or e.KeyChar = "1") Then
Else
e.Handled = True
End If
End If
End Sub

VB2010: Allow Float/Integers, Backspace, and Range of Value in Textbox

I've one Textbox in Visual Basic (Visual Studio 2010, .net frame work 4.0)
Now I have a problem!
I want that user only Enter Integer, float, backspace and range of value?
Confused?
Oh yeah
I want that user only Enter value in between 0 - 4 (value may be in decimal as 3.49)
Now I want complete code:
I have this:
This is working , but I am unable to specifies the range between 0-4
Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As
System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
Dim FullStop As Char
FullStop = "."
' if the '.' key was pressed see if there already is a '.' in the string
' if so, dont handle the keypress
If e.KeyChar = FullStop And TextBox1.Text.IndexOf(FullStop) <> -1 Then
e.Handled = True
Return
End If
' If the key aint a digit
If Not Char.IsDigit(e.KeyChar) Then
' verify whether special keys were pressed
' (i.e. all allowed non digit keys - in this example
' only space and the '.' are validated)
If (e.KeyChar <> FullStop) And
(e.KeyChar <> Convert.ToChar(Keys.Back)) Then
' if its a non-allowed key, dont handle the keypress
e.Handled = True
Return
End If
End If
End Sub
Please if some one give me the complete code for this so I will be very happy
Thanks in advance
I just used the Benifits of ascii codes of characters to solve your problem,
Try this out, If you have any doubts in the following implementation, then feel free to comment me back.
Private Sub TextBox1_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
'Ascii code 8 for backspace -- Ascii code 46 for (. period)
If Asc(e.KeyChar) = 8 Or Asc(e.KeyChar) = 46 Then
'If typed character is a period then we have to ensure that more than one of it
'Should not get allowed to type. And also we have to check whether the period symbol
'may cause any conflicts with MaxNo that is 4
If Asc(e.KeyChar) = 46 Then
If TextBox1.Text.IndexOf(".") <> -1 Or Val(TextBox1.Text.Trim & e.KeyChar) >= 4 Then
e.Handled = True
Else
Exit Sub
End If
Else
'If pressed key is backspace, then allow it.
Exit Sub
End If
End If
'Checking whether user typing more than 4 or not.
If Val(TextBox1.Text.Trim & e.KeyChar) > 4 Then
e.Handled = True
End If
'48 - 57 = Ascii codes for numbers
If (Asc(e.KeyChar) < 48 Or Asc(e.KeyChar) > 57) Then
e.Handled = True
End If
End Sub

limit the range of characters the user can put into a textbox vb.net

I have a textbox in a vb form and I want to limit the range of characters that the user can put into the textbox to:" abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890^-*().". The textbox is to insert SI Units into a database so i need consistent syntax. If the user types an invalid character into the textbox I would like the textbox to refuse to insert it, or remove it straight away, leaving the cursor in the same position within the textbox. I would also like the textbox to replace "/" with "^(-" and place the cursor before this.
I have found some code elsewhere which I have edited to do this but the code is bad, it activates on text changed within the textbox. This causes the code to fail, when the user inputs a disallowed value the code it activates itself when it tries to changes the text within the textbox.
Here is my code, the textbox starts with the contents "enter SI Units" from the form designer.
Private Sub TxtQuantityTextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtSIUnit.TextChanged
If txtSIUnit.Text = "Enter SI Units" Then
Exit Sub
End If
Dim charactersAllowed As String = " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890^-*()."
Dim Text As String = txtSIUnit.Text
Dim Letter As String
Dim SelectionIndex As Integer = txtSIUnit.SelectionStart
Dim Change As Integer
Letter = txtSIUnit.Text.Substring(SelectionIndex - 1, 1)
If Letter = "/" Then
Text = Text.Replace(Letter, "^(-")
SelectionIndex = SelectionIndex - 1
End If
Letter = txtSIUnit.Text.Substring(SelectionIndex - 1, 1)
If charactersAllowed.Contains(Letter) = False Then
Text = Text.Replace(Letter, String.Empty)
Change = 1
End If
txtSIUnit.Text = Text
txtSIUnit.Select(SelectionIndex - Change, 0)
If txtQuantity.Text <> "Enter Quantity" Then
If cmbStateRateSumRatio.SelectedIndex <> -1 Then
bttAddQUAtoDatabase.Enabled = True
End If
End If
End Sub`
Thanks for you help.
Use the KeyPress event. Set e.Handled to true if you don't like the character. It's a one-liner:
Private Const AllowedChars = " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890^-*()."
Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As PressEventArgs) Handles TextBox1.KeyPress
If e.KeyChar >= " "c AndAlso Not AllowedChars.Contains(e.KeyChar) Then e.Handled = True
End Sub
In the textbox's KeyDown event, check e.KeyCode. This lets you prevent certain characters from being handled. There's an example on the KeyDown documentation.

How to filter textbox input to numeric only?

How do I suppress all data except numeric?
This is not working on KeyDown():
If e.KeyData < Keys.D0 Or e.KeyData > Keys.D9 Then
e.Handled = True
End If
There are many ways to do this. I've had a quick stab at it and go this which works. I have used the KeyPress sub for the textbox, and pass each keypress to the IsNumber function.
NOTE: I have allowed the backspace key to be used in case you make a mistake with the numbers and want to deleted.
Take out the If e.KeyChar <> ChrW(Keys.Back) Then / End If part if you dont need the backspace.
Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
If e.KeyChar <> ChrW(Keys.Back) Then
If Char.IsNumber(e.KeyChar) Then
Else
e.Handled = True
End If
End If
End Sub
You can check Char.IsDigit(e.KeyChar), but the best thing to do in this case is to create a subclass of TextBox and override IsInputChar(). That way you have a reusable TextBox control that you can drop anywhere so you don't have to re-implement the logic.
(My VB is a bit rusty...)
Public Class NumericTextBox : Inherits TextBox
Protected Overrides Function IsInputChar(Byval charCode As Char) As Boolean
If (Char.IsControl(charCode) Or Char.IsDigit(charCode)) Then
Return MyBase.IsInputChar(charCode)
Else
Return False
End If
End Function
End Class
This code will help you to restrict multiple TEXTBOX to accept only NUMERIC VALUE and BACKSPACE key. However you can remove If e.KeyChar <> ChrW(Keys.Back) Then and End If value from code when you don't want to accept backspace key. Enhanced version of the kevchadders solution in this thread.
Private Sub TextBox_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress, TextBox2.KeyPress, TextBox3.KeyPress
If e.KeyChar <> ChrW(Keys.Back) Then
If Char.IsNumber(e.KeyChar) Then
Else
e.Handled = True
End If
End If
End Sub
Will help you...
Public Function IsNumericTextbox(ByVal sender As TextBox, ByVal KeyChar As Char) As Boolean
'set TRUE: cause a exception when the keychar is not Allowed into vars: allowedChars, allowedOneChar, allowedExceptionChar
Dim UseThrowDebuggy As Boolean = False
Dim allowedChars As String = "0123456789"
Dim allowedOnceChar As Char() = {"."}
Dim allowedExceptionChar As Keys() = {Keys.Back}
Dim idxAllowedNotFound As Integer
Dim idxCountOne As Integer = 0
idxAllowedNotFound = allowedChars.IndexOf(KeyChar)
If idxAllowedNotFound = True Then
'AllowedOnce
For Each _c As Char In allowedOnceChar
If _c = KeyChar Then
'Count Check
For Each _cc As Char In sender.Text
If _c = _cc Then idxCountOne += 1
Next
If idxCountOne = 0 Then
Return False
Else
Return True
End If
End If
Next
'Exceptions
For i As Integer = 0 To allowedExceptionChar.Count - 1
If Asc(KeyChar) = Convert.ToUInt32(allowedExceptionChar(i)) Then Return False
Next
'Not Throw
If UseThrowDebuggy = False Then
If Char.IsNumber(KeyChar) Then
Return False
Else
Return True
End If
End If
'Outside to end for throw
Else
'AllowedChars
Return False
End If
Dim _kc As String = ControlChars.NewLine & "Char: " & KeyChar & ControlChars.NewLine & "Asc: " & Asc(KeyChar) & ControlChars.NewLine
Throw New Exception("UseThrowDebuggy found a unknow KeyChar: " & _kc)
End Function
For use my function add this code into a textbox_keypress:
e.Handled = IsNumericTextbox(sender, e.KeyChar)
Public Class NumericTextBox : Inherits System.Windows.Forms.TextBox
Protected Overrides Sub OnKeyPress(e As Windows.Forms.KeyPressEventArgs)
If Char.IsDigit(e.KeyChar) Or
Char.IsControl(e.KeyChar) Or
e.KeyChar = lobalization.CultureInfo.CurrentCulture.NumberFormat.CurrencyDecimalSeparator Then
MyBase.OnKeyPress(e)
Else
e.Handled = True
End If
End Sub
End Class
I suggest that you use regular expressions. You can search Google, like 'regular expression textbox only numeric' and I guess you'll come up with many examples.
For example, if you are in ASP.NET you can do it like:
<asp:TextBox
ID="txtPhoneNumber"
runat="server"
Text='<%#Bind("phoneNumber") %>'
MaxLength="15">
</asp:TextBox>
<asp:RegularExpressionValidator
ID="rfvUSerPhoneNumberValidate"
runat="server"
ControlToValidate="txtPhoneNumber"
Display="Dynamic"
ValidationExpression="^[0-9]{1,15}$"
ErrorMessage="Please enter only numeric value for Phone Number"
EnableViewState="true">
</asp:RegularExpressionValidator>
This will allow numeric input ,Backspace to correct your input , and also a decimal point.
If (e.KeyChar < "0" OrElse e.KeyChar > "9") AndAlso e.KeyChar <> ControlChars.Back AndAlso e.KeyChar <> ControlChars.Cr AndAlso e.KeyChar <> "." Then
Beep()
e.Handled = True
End If
This is another way to restrict number inputs into textbox . using KEYPRESS Events
If Asc(e.KeyChar) <> 13 AndAlso Asc(e.KeyChar) <> 8 AndAlso Not IsNumeric(e.KeyChar) Then
MessageBox.Show("Only Numbers")
e.Handled = True
End If
End Sub
hope it helps ! thnks ..
The purpose of your function could help provide additional solutions. Checking for a numeric value on each KeyPress is likely overkill. Then you have to overkill it more by accounting for backspace, delete, copy, paste, etc.
For example, if you are storing a telephone number, you should use the "IsNumeric" function on the validate and update step. Alternatively, if you are selecting quantity of an item "NumericUpDown" control would be more appropriate than a TextBox.