Questions

Text Box Validation in VB.NET

+
1 Votes
Locked

Text Box Validation in VB.NET

brianmilke
How do I validate a text Box input so that only numeric values can be input and no other characters?
+
1 Votes
brianmilke

heres the code I am using to validate the TextBox.Text Input...

Private Sub TextBox1_Validating(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles TextBox1.Validating
' Determines if input is number, or if it is a correct value 1 - 100
If Not IsNumeric(TextBox1.Text) Or Val(TextBox1.Text) < 0 Or Val(TextBox1.Text) > 100 Then
MessageBox.Show("Only use numbers 0 or 1 - 100", "Input Error")

'Selects the whole string as highlighted for deletion when next input is given
TextBox1.SelectionStart = 0
TextBox1.SelectionLength = TextBox1.Text.Length

' Determines if the cursor should return to the textbox for input change
e.Cancel = True
Else : e.Cancel = False
End If
End Sub

+
0 Votes
whittle1gh

Private Sub BtnEnterDiesel_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnEnterDiesel.Click
If Me.TxtUnitpriceDiesel.Text <> "" Then
If Me.TxtQtyDiesel.Text <> "" Then
If IsNumeric(Me.TxtQtyDiesel.Text) And IsNumeric(Me.TxtUnitpriceDiesel.Text) Then

Call addtankreadings()
Else : MsgBox("Must be in digits")
End If

Else : MsgBox("Quantity cannot be empty")
End If

Else : MsgBox("Enter the Unit Price")
End If

End Sub

+
0 Votes
arvind.lnct

function isNumberKey(evt)
{
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57) )
{
alert("Numeric Only");
return false;
}
return true;
}

on code-behind:
Textbox1.Attributes.Add("onkeypress", "return isNumberKey(event)")

+
0 Votes
vaduganathanmaster

Why don't you valid the keys on KeyPress event with the help of IsDegit function to validate the current key is Numeric or not.

With the help of the decision you made either you can allow the key to proceed or not.

I hope this will resolve your requirement. However, if not, please do reply.

I will be glad to assist you.

+
0 Votes
Mehul Bhai

Zombie Alert!!!

+
0 Votes
carl_batch2003

Private Sub txtNotNumeric_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtNotNumeric.KeyPress
If IsNumeric(e.KeyChar) Then
e.Handled = True
End If
End Sub

+
0 Votes
Mehul Bhai

Zombie Alert!!!

+
0 Votes
Mehul Bhai

Zombie Alert!!!

+
0 Votes
Tony Hopkinson

They'll all return at some point, probably after some user complains the backspace, decimal point and minus keys don't work....