Reputation:
in my application I need to validate mobile number text field in different forms. so I wish to write a function for this purpose.my needs are:
text field accept only numbers(0-9). error message will shown if any other characters are entered. does't allow space but allow ctrl+c,ctrl+v,ctrl+x ans back sapce. if ctrl+v(paste) is done it will check whether the string contains characters, if yes then display error message. does anyone can help me to write such a function in limited number of code?
I had validated the following
Private Sub mob_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles stok.KeyPress
If Asc(e.KeyChar) < 48 Or Asc(e.KeyChar) > 57 Then ' check whether the keypress is a number
mob.ForeColor = Color.green
Else
mob.ForeColor = Color.Red
end if
end sub
Private Sub mob_LostFocus(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles stok.KeyPress
if mob.text="" then 'for check empty space
end sub
but this is not what I need. I need all the process executed within a function
Upvotes: 0
Views: 2851
Reputation: 10889
I think a regular expression would be best for your needs, take a look at this:
http://www.authorcode.com/how-to-use-regular-expression-for-validating-phone-numbers-in-net/
As a side note: I find the Asc(e.KeyChar) extremely ugly, I would parse the char to an int and see what happens: If int.TryParse() fails: error, if not: well it's a number.
Upvotes: 1
Reputation: 1326
Public Sub mob_validation(ByVal e As System.Windows.Forms.KeyPressEventArgs, ByVal mob As TextBox)
If e.KeyChar = Chr(22) Then
Dim output As String = New String((From c As Char In Clipboard.GetText.ToString Select c Where Char.IsLetter(c)).ToArray())
If output = "" And Len(mob.Text) = 10 Then
mob.ForeColor = Color.Green
Else
mob.ForeColor = Color.Red
Clipboard.Clear()
End If
Else
If Asc(e.KeyChar) < 48 Or Asc(e.KeyChar) > 57 Then
If Asc(e.KeyChar) <> 8 Then
If Asc(e.KeyChar) <> 3 Then
e.Handled = True
mob.ForeColor = Color.Red
End If
End If
Else
mob.ForeColor = Color.Green
End If
End If
End Sub
Upvotes: 0