How to tips and tricks for Microsoft Visual Studio .net

Tuesday, May 15, 2018

Validate South African ID Number

The South African ID Number is a unique number given to every person who is a South African citizen, or who has been granted permanent South African residence. Use this site to find out how the number is made up.

The South African ID Number can be validated using the Luhn algorithm.

I use the following code to validate South African ID Numbers in my applications:

vb.net

Public Shared Function RSA_ID_Number(ByVal id_no As String) As Boolean
        Dim is_valid As Boolean = False

        Try
            If id_no.Length = 13 Then
                Dim intcheck_a As Integer = 0
                Dim strCheck_b As String = ""
                Dim intcheck_b As Integer = 0
                Dim intCheck_c As Integer = 0
                Dim check_calc_result As Integer = 0
                Dim check_digit As Integer = id_no.Substring(12, 1)

                ' Step 1
                For i = 0 To id_no.Length - 1
                    Select Case i
                        Case 0, 2, 4, 6, 8, 10
                            intcheck_a += Convert.ToInt64(id_no.Substring(i, 1))
                        Case 1, 3, 5, 7, 9, 11
                            strCheck_b &= id_no.Substring(i, 1)
                    End Select
                Next

                ' Step 2
                intcheck_b = Convert.ToInt64(strCheck_b) * 2
                strCheck_b = intcheck_b.ToString()

                ' Step 3
                intcheck_b = 0
                For i As Integer = 0 To strCheck_b.Length - 1
                    intcheck_b += Convert.ToInt64(strCheck_b.Substring(i, 1))
                Next

                ' Step 4
                intCheck_c = intcheck_a + intcheck_b

                check_calc_result = 10 - intCheck_c.ToString.Substring(intCheck_c.ToString.Length - 1, 1)

                is_valid = check_calc_result = check_digit
            End If

        Catch ex As Exception : Throw

        End Try

        Return is_valid
    End Function

No comments:

Post a Comment