[VB.net]身分證字號驗證程序(一)

[VB.net]身分證字號驗證程序

中華民國身分證字號編碼方式:參考維基網站

 

用 VB.net 寫成函式(含表單 Code):

Public Class Form1
    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
        Dim 縣市 As String = ""
        Dim 性別 As String = ""
        Dim 號碼 = MaskedTextBox1.Text
        MsgBox(分析身分證字號(號碼, 縣市, 性別) & vbCrLf & 號碼 & vbCrLf & 縣市 & vbCrLf & 性別)
    End Sub
    Private Function 分析身分證字號(ByRef 字號 As String, Optional ByRef 縣市 As String = "", Optional ByRef 性別 As String = "") As Boolean
        '---先驗證號碼是否錯誤---
        If 字號 <> "" AndAlso Not IsNumeric(字號.First) AndAlso IsNumeric(Mid(字號, 2)) Then
            字號 = UCase(字號)
            Const 縣市編碼索引字串 As String = "ABCDEFGHJKLMNPQRSTUVXYWZIO"
            Dim 驗證字串 = CStr(InStr(縣市編碼索引字串, UCase(字號.First)) + 9) & Mid(字號, 2)
            Dim 驗算值 As Integer = Val(驗證字串.First) + Val(驗證字串.Last)
            For i = 2 To 10
                驗算值 += Val(Mid(驗證字串, i, 1)) * (11 - i)
            Next
            If 驗算值 Mod 10 Then Return False
        Else
            Return False
        End If
        '---驗證通過繼續剖析內容---
        Dim 縣市陣列 As Array =
        {
            "A台北市", "B台中市", "C基隆市", "D台南市", "E高雄市", "F台北縣", "G宜蘭縣", "H桃園縣", "I嘉義市",
            "J新竹縣", "K苗栗縣", "L台中縣", "M南投縣", "N彰化縣", "O新竹市", "P雲林縣", "Q嘉義縣", "R台南縣",
            "S高雄縣", "T屏東縣", "U花蓮縣", "V台東縣", "W金門縣", "X澎湖縣", "Y陽明山", "Z連江縣"
        }
        Dim Id = Asc(UCase(字號.First)) - 65
        縣市 = Mid(縣市陣列(Id), 2)
        性別 = Mid("男女", Val(Mid(字號, 2, 1)), 1)
        Return True
    End Function

 

初步測試是OK的,繼續再是否有什麼 bug 或防呆沒做好的地方......

image


ku3