Spanish Calculo DNI/NIE letra

Similar threads

B4R Code Snippet JSON Parsing
B4A Code Snippet CSBuilder marking based on regex pattern
B4A Tutorial Discovering iBeacon devices with BLE2 library
B4R Tutorial Strings and Bytes
B4A Code Snippet Proper Case For Names

scsjc

Well-Known Member
Licensed User
Hola a todos,
Os comparto aqui un antiguo codigo para verificar o extraer la letra del DNI/NIE

B4X:
Log(getLetraDNI("45538415")) '<--- devuelve letra
Log(checkDNI("Y2881542R")) ' <--- devuelve correcto o incorrecto


Sub checkDNI(dni As String) As String
    If dni.Length<>9 Then Return False 'longitud incorrecta
    dni = dni.ToUpperCase
    Dim txtlongitud As Int = dni.Length
    Dim letra As String = dni.SubString2(txtlongitud-1,txtlongitud)
    Dim letracalculada As String = getLetraDNI(dni.SubString2(0,txtlongitud-1))
    If letra=letracalculada Then Return True Else Return False
End Sub
Sub getLetraDNI(dni As String) As String
    If dni.Length<>8 Then Return "" 'longitud incorrecta
    dni = dni.ToUpperCase
    ' Si es un NIE hay que cambiar la primera letra por 0, 1 ó 2 dependiendo de si es X, Y o Z.
    Dim primeraletra As String = dni.SubString2(0,1)
    Select Case primeraletra
        Case "X":
            dni = dni.Replace("X","0")
        Case "Y":
            dni = dni.Replace("Y","1")
        Case "Z":
            dni = dni.Replace("Z","2")
    End Select
    Dim letras As String = "TRWAGMYFPDXBNJZSQVHLCKE"
    Dim character As Int
    character = (1 + (dni) Mod 23)
    Return letras.SubString2 ((character-1), (character-1)+ 1)
End Sub
Saludos
 
Top