验证vb.net上的电话号码 [英] validate phone number on vb.net

查看:143
本文介绍了验证vb.net上的电话号码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用vb.net在Visual Studio中有一个常规表单(不是Windows窗体)。一旦它失去了重点,我想验证电话领域,当用户选择了外地的时候。如何举办活动?丢失的焦点事件不会出现下拉列表?
谢谢。
〜Nita

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

推荐答案

您可以使用以下方法验证电话号码。

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

并在您的代码前端

<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>

这篇关于验证vb.net上的电话号码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆