问题
I have a regular form(not windows form) in Visual Studio using vb.net. I would like to validate the phone field once it looses focus, in the sense when the user tabs out of the field. How do I raise an event? The dropdown doesn't come with lostfocus event? Thanks. ~ Nita
回答1:
You can use the method below to validate phone number. Just pass a phone number argument into the method.
Protected Sub txtPhone_TextChanged(sender As Object, e As EventArgs) Handles txtPhone.TextChanged
If Not IsPhoneNumberValid(txtPhone.Text) Then
Dim isvalid = False
lblValidatioMessage.Visible = True
lblValidatioMessage.Text = "*Invalid Phonenumber"
Else
lblValidatioMessage.Visible = False
lblValidatioMessage.Text = ""
End If
End Sub
Private Shared Function IsPhoneNumberValid(phoneNumber As String) As Boolean
Dim result As String = ""
Dim chars As Char() = phoneNumber.ToCharArray()
For count = 0 To chars.GetLength(0) - 1
Dim tempChar As Char = chars(count)
If [Char].IsDigit(tempChar) Or "()+-., ".Contains(tempChar.ToString()) Then
result += StripNonAlphaNumeric(tempChar)
Else
Return False
End If
Next
Return result.Length = 10 'Length of US phone numbers is 10
End Function
Private Shared Function StripNonAlphaNumeric(value As String) As String
Dim regex = New Regex("[^0-9a-zA-Z]", RegexOptions.None)
Dim result As String = ""
If regex.IsMatch(value) Then
result = regex.Replace(value, "")
Else
result = value
End If
Return result
End Function
and in your code front
<asp:Label ID="lblPhone" runat="server" Text="Phone"></asp:Label>
<p><asp:TextBox ID="txtPhone" runat="server" AutoPostBack="True"></asp:TextBox></p>
<asp:Label ID="lblValidatioMessage" Visible="False" runat="server" Text="" ForeColor="red"></asp:Label>
回答2:
Try to use the Control.Validating and Control.Validated events. Basically, the Validating event is designed for validation. If the phone # isn't valid, set e.Cancel = True, and the focus will stay on that field.
The following code example uses the derived class TextBox and validates an e-mail address that the user enters. If the e-mail address is not in the standard format (containing "@" and "."), the validation fails, an ErrorProvider icon is displayed, and the event is canceled. This example requires that a TextBox and ErrorProvider control have been created on a form. - Source
Private Function ValidEmailAddress(ByVal emailAddress As String, ByRef errorMessage As String) As Boolean
' Confirm there is text in the control.
If textBox1.Text.Length = 0 Then
errorMessage = "E-mail address is required."
Return False
End If
' Confirm that there is an "@" and a "." in the e-mail address, and in the correct order.
If emailAddress.IndexOf("@") > -1 Then
If (emailAddress.IndexOf(".", emailAddress.IndexOf("@")) > emailAddress.IndexOf("@")) Then
errorMessage = ""
Return True
End If
End If
errorMessage = "E-mail address must be valid e-mail address format." + ControlChars.Cr + _
"For example 'someone@example.com' "
Return False
End Function
Private Sub textBox1_Validating(ByVal sender As Object, _
ByVal e As System.ComponentModel.CancelEventArgs) Handles textBox1.Validating
Dim errorMsg As String
If Not ValidEmailAddress(textBox1.Text, errorMsg) Then
' Cancel the event and select the text to be corrected by the user.
e.Cancel = True
textBox1.Select(0, textBox1.Text.Length)
' Set the ErrorProvider error with the text to display.
Me.errorProvider1.SetError(textBox1, errorMsg)
End If
End Sub
Private Sub textBox1_Validated(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles textBox1.Validated
' If all conditions have been met, clear the error provider of errors.
errorProvider1.SetError(textBox1, "")
End Sub
回答3:
Private Function IsPhoneNumberValid(ByVal Number As String) As Boolean
dim PhoneValid As boolean
Dim PhoneNumber As String = "^[1-9]\d{2}-[1-9]\d{2}-\d{4}$"
Dim ChekPhone As New Regex(PhoneNumber )
If Not String.IsNullOrEmpty(Number ) Then
PhoneValid = ChekPhone.IsMatch(Number )
Else
PhoneValid = False
End If
Return PhoneValid
End Function
Private Sub txtPhoneNumber_LostFocus(sender As Object, e As System.EventArgs) Handles txtPhoneNumber.LostFocus
If Not IsPhoneNumberValid(txtPhoneNumber.Text) Then
MessageBox.Show("Please Enter Phone Number!")
txtPhoneNumber.Clear()
txtPhoneNumber.Focus()
End If
End Sub
来源:https://stackoverflow.com/questions/24894005/validate-phone-number-on-vb-net