NIF,NIE,CIF验证器grails

时间:2015-12-23 14:59:22

标签: validation grails groovy

我一直在为NIE,NIF或CIF这样的西班牙ID寻找验证器,但是我找不到一个用groovy写的东西是不可能的。这就是我在这里的原因。我必须在javascript(http://www.yporqueno.es/blog/as3-validar-nif-cif-y-nie)中使用此代码并将其修改为在groovy上工作。

由于我是新人,我不确定是否在这里我必须写这个,如果我做错了,我希望有人纠正我。

这是我的班级:

class TestDniService {
//--------------------------------------------------------------------------
public Boolean isNif(String a) {
    int numero
    String dni=a.toUpperCase();
  //  def letra = dni.substring(dni.length())
    try{
        println"try "+dni.substring(0,dni.length()-1)
        numero =dni.substring(0,dni.length()-1).toInteger()
    }catch (NumberFormatException num){
        return false
    }
    String let = dni.substring(dni.length()-1)
    let=let.toUpperCase();
    numero=numero%23;
    String letra='TRWAGMYFPDXBNJZSQVHLCKET';
    String lletra =letra.charAt(numero);
    return (lletra == let);//devuelve true o false
}//End isNif

//--------------------------------------------------------------------------
public Boolean isNie(String a) {
    String dni=a.toUpperCase();
    String pre=dni.substring(0,1);
    String prev="0";
    if (pre=="X") {
        prev="0";
    } else if (pre == "Y") {
        prev="1";
    } else if (pre == "Z") {
        prev="2";
    }
    String numero = prev.toString()+dni.substring(1,dni.length()).toString()
    return isNif(numero);//una vez tratamos el NIE lo comprovamos como un NIF
}//End isNie

//--------------------------------------------------------------------------
public Boolean isCif(String cif) {
    println"CIF inicial "+cif
    def pares = 0;
    def impares = 0;
    def suma;
    def ultima;
    def unumero;
    def uletra = ["J", "A", "B", "C", "D", "E", "F", "G", "H", "I"]
    def xxx;

    String texto=cif.toUpperCase()
    if (!texto ==~ /^[ABCDEFGHJKLMNPQS]\d{7}[0-9,A-J]$/) {
        return false;
    }

    ultima = texto.substring(8,9)
    pares = texto.substring(2,3).toInteger()+texto.substring(4,5).toInteger()+texto.substring(6,7).toInteger()

    for (int cont = 1 ; cont <= 7 ; cont++){
        xxx = 2 * texto.substring(cont,cont+1).toInteger()
        if (xxx > 9) while (xxx > 9){
            xxx =  xxx.toString().substring(0,1).toInteger()+ xxx.toString().substring(1,2).toInteger()
        }
        impares += xxx
        cont++
    }

    suma = (pares + impares).toString();
    unumero = suma.substring(suma.length() - 1,suma.length()).toInteger()
    unumero = (10 - unumero).toString();
    if (unumero.toInteger() == 10) unumero = 0;
    if ((ultima.toString() == unumero.toString()) || (ultima == uletra[unumero.toInteger()]))
        return true;
    else
        return false;
}//End isCif

//--------------------------------------------------------------------------
public int testAll(String dni) {
    String cadena = dni.toUpperCase();//convertimos a mayusculas
    String pre= cadena.substring(0,1);//extraemos el primer digito o letra
    if (pre=="X"||pre=="Y"||pre=="Z") {//Si el primer digito es igual a X,Y o Z entonces es un NIE
        if (isNie(dni)) {//llamamos a la funcion testNIE(); pasandole por parametro el dni. Devolvera true o false
            return 1;//Si es true devolvemos 1, 1 = NIE correcto.
        } else {
            return -1;//Si es false devolvemos -1, -1 = NIE incorrecto.
        }
    } else {//Si no es un NIE comprovamos si es un CIF
        if (pre ==~ (/[ABCDEFGHJKLMNPQRSUVW]/)) {//Si la primera letra de la cadena coincide con alguna del patron letrasCIF entonces es un CIF
            if (isCif(dni)) {//llamamos a la funcion testCIF(); pasandole por parametro el dni. Devolvera true o false
                return 2;//Si es true devolvemos 2, 2 = CIF correcto.
            } else {
                return -2;//Si es false devolvemos -2, -2 = CIF incorrecto.
            }
        } else {//Si no es un CIF comprovamos si es un NIF
            if (pre ==~ (/[1234567890]/)) {//Si el primer digito de la cadena coincide con el patron numerosNIF entonces es un NIF
                if (isNif(dni)) {//llamamos a la funcion testNIF(); pasandole por parametro el dni. Devolvera true o false
                    return 3;//Si es true devolvemos 3, 3 = NIF correcto.
                } else {
                    return -3;//Si es false devolvemos -3, -3 = NIF incorrecto.
                }
            } else {//Si tampoco es un NIF entonces no es un dni valido de ningun tipo
                //si no es ninguno devolvemos 0
                return 0;
            }
        }
    }
}//End function test


}

我希望它能帮到任何人。

2 个答案:

答案 0 :(得分:1)

这是我的课程:

class TestDniService {
//--------------------------------------------------------------------------
public Boolean isNif(String a) {
    int numero
    String dni=a.toUpperCase();
  //  def letra = dni.substring(dni.length())
    try{
        println"try "+dni.substring(0,dni.length()-1)
        numero =dni.substring(0,dni.length()-1).toInteger()
    }catch (NumberFormatException num){
        return false
    }
    String let = dni.substring(dni.length()-1)
    let=let.toUpperCase();
    numero=numero%23;
    String letra='TRWAGMYFPDXBNJZSQVHLCKET';
    String lletra =letra.charAt(numero);
    return (lletra == let);//devuelve true o false
}//End isNif

//--------------------------------------------------------------------------
public Boolean isNie(String a) {
    String dni=a.toUpperCase();
    String pre=dni.substring(0,1);
    String prev="0";
    if (pre=="X") {
        prev="0";
    } else if (pre == "Y") {
        prev="1";
    } else if (pre == "Z") {
        prev="2";
    }
    String numero = prev.toString()+dni.substring(1,dni.length()).toString()
    return isNif(numero);//una vez tratamos el NIE lo comprovamos como un NIF
}//End isNie

//--------------------------------------------------------------------------
public Boolean isCif(String cif) {
    println"CIF inicial "+cif
    def pares = 0;
    def impares = 0;
    def suma;
    def ultima;
    def unumero;
    def uletra = ["J", "A", "B", "C", "D", "E", "F", "G", "H", "I"]
    def xxx;

    String texto=cif.toUpperCase()
    if (!texto ==~ /^[ABCDEFGHJKLMNPQS]\d{7}[0-9,A-J]$/) {
        return false;
    }

    ultima = texto.substring(8,9)
    pares = texto.substring(2,3).toInteger()+texto.substring(4,5).toInteger()+texto.substring(6,7).toInteger()

    for (int cont = 1 ; cont <= 7 ; cont++){
        xxx = 2 * texto.substring(cont,cont+1).toInteger()
        if (xxx > 9) while (xxx > 9){
            xxx =  xxx.toString().substring(0,1).toInteger()+ xxx.toString().substring(1,2).toInteger()
        }
        impares += xxx
        cont++
    }

    suma = (pares + impares).toString();
    unumero = suma.substring(suma.length() - 1,suma.length()).toInteger()
    unumero = (10 - unumero).toString();
    if (unumero.toInteger() == 10) unumero = 0;
    if ((ultima.toString() == unumero.toString()) || (ultima == uletra[unumero.toInteger()]))
        return true;
    else
        return false;
}//End isCif

//--------------------------------------------------------------------------
public int testAll(String dni) {
    String cadena = dni.toUpperCase();//convertimos a mayusculas
    String pre= cadena.substring(0,1);//extraemos el primer digito o letra
    if (pre=="X"||pre=="Y"||pre=="Z") {//Si el primer digito es igual a X,Y o Z entonces es un NIE
        if (isNie(dni)) {//llamamos a la funcion testNIE(); pasandole por parametro el dni. Devolvera true o false
            return 1;//Si es true devolvemos 1, 1 = NIE correcto.
        } else {
            return -1;//Si es false devolvemos -1, -1 = NIE incorrecto.
        }
    } else {//Si no es un NIE comprovamos si es un CIF
        if (pre ==~ (/[ABCDEFGHJKLMNPQRSUVW]/)) {//Si la primera letra de la cadena coincide con alguna del patron letrasCIF entonces es un CIF
            if (isCif(dni)) {//llamamos a la funcion testCIF(); pasandole por parametro el dni. Devolvera true o false
                return 2;//Si es true devolvemos 2, 2 = CIF correcto.
            } else {
                return -2;//Si es false devolvemos -2, -2 = CIF incorrecto.
            }
        } else {//Si no es un CIF comprovamos si es un NIF
            if (pre ==~ (/[1234567890]/)) {//Si el primer digito de la cadena coincide con el patron numerosNIF entonces es un NIF
                if (isNif(dni)) {//llamamos a la funcion testNIF(); pasandole por parametro el dni. Devolvera true o false
                    return 3;//Si es true devolvemos 3, 3 = NIF correcto.
                } else {
                    return -3;//Si es false devolvemos -3, -3 = NIF incorrecto.
                }
            } else {//Si tampoco es un NIF entonces no es un dni valido de ningun tipo
                //si no es ninguno devolvemos 0
                return 0;
            }
        }
    }
}//End function test


}

我希望它能帮助任何人。

@gsan提供的答案

答案 1 :(得分:0)

这是在生产中工作的完整示例:

想象一个User类,其中包含以下字段:

class User implements Serializable {
    String documentNumber
    DocumentType documentType

    static constraints = {
        documentNumber (blank: false, nullable: true, unique: true, validator: { val, obj ->
            //Provide a documentType and the documentNumber to the validate method
            return DocumentType.validateDocument(DocumentType.get(obj.properties['documentType'].toString()), (String)val)
        })
        documentType (blank: false, nullable: true)
    }
}

这是实用程序类:

看看static boolean validateDocument (DocumentType type, String value)

public enum DocumentType implements org.springframework.context.MessageSourceResolvable {
    CIF('CIF'),
    NIF('NIF'),
    DNI('DNI'),
    NIE('NIE'),
    PASSPORT('Passport')

    String id

    DocumentType(String id) {
        this.id = id
    }

    static DocumentType get(String id) {
        values().find { it.id == id }
    }

    public Object[] getArguments() { [] as Object[] }

    public String[] getCodes() { ["documentType." + name()] as String[] }

    public String getDefaultMessage() { name() }

    @Override
    String toString() {
        return this.id
    }

    /** Utilities **/
    static def CIF_REGEX = /[ABCDEFGHJNPQRSUVW]{1}[0-9]{7}[ABCDEFGHJNPQRSUVW0-9]{1}$/
    static def NIF_REGEX = /[0-9]{8}[A-Z]{1}$/
    static def DNI_REGEX = NIF_REGEX
    static def NIE_REGEX = /[XYZ]{1}[0-9]{7}[A-Z]{1}$/
    static def PASSPORT_REGEX = /^([ABCDEFGHJKLMNPQRSUVW])(\d{7})([0-9A-J])$/

    static String validationChars = "TRWAGMYFPDXBNJZSQVHLCKE"

    static boolean validateCIF (String value) {
        if ( (value =~ CIF_REGEX) ) {
            //calculamos el numero de control
            int A = 0, B = 0, C = 0
            String middleNumbers = value.substring(1, 8)
            Integer controlNumber = 0

//            A = Character.getNumericValue(middleNumbers.charAt(1)) + Character.getNumericValue(middleNumbers.charAt(3)) + Character.getNumericValue(middleNumbers.charAt(5))

            for (int i = 1; i < middleNumbers.length(); i += 2) {
                A += Integer.parseInt(middleNumbers.substring(i, i + 1));
            }

            for (int i = 0; i < middleNumbers.length(); i += 2) {
                Integer aux = Integer.parseInt(middleNumbers.substring(i, i + 1)) * 2;
                if (aux.toString().length() > 1) {
                    aux = Integer.parseInt(aux.toString().substring(0, 1)) + Integer.parseInt(aux.toString().substring(1, 2));
                }
                B += aux;
            }

            C = (A + B)
            controlNumber = 10 - (C % 10)

            String finalChar = Character.toString( value.charAt(8) )
            String controlCharacter = Character.toString( (char)(64 + controlNumber) )

            println controlNumber.toString()
            println Character.toString( (char)(64 + controlNumber) )
            println finalChar

            if( controlCharacter == finalChar ){
                return true
            } else {
                controlNumber = controlNumber == 10 ? 0 : controlNumber
                if ( controlNumber.toString() == finalChar ) {
                    return true
                }
            }
        }
        return false
    }

    static boolean validateNIF (String value) {
        if ( (value =~ NIF_REGEX) ) {
            int position = ( Integer.parseInt( value.substring(0, 8) ) ) % 23
            char letter = validationChars.charAt( position )
            if(letter == value.charAt(8)){
                return true
            }
        }
        return false
    }

    static boolean validateDNI (String value) {
        return validateNIF(value)
    }

    static boolean validateNIE (String value) {
        if ( (value ==~ NIE_REGEX) ) {
            value = value.replace( 'X','0' )
            value = value.replace( 'Y','1' )
            value = value.replace( 'Z','2' )
            return validateDNI (value)
        }
        return false
    }

    static boolean validatePassport (String value) {
        //La validación de pasaporte depende de cada pais
        return true
    }

    static boolean validateDocument (DocumentType type, String value) {
        boolean result = true
        if (value != null && value != "") {
            value = value.toUpperCase().trim()

            switch (type) {
                case CIF:
                    result = validateCIF (value)
                    break;
                case NIF:
                case DNI:
                    result = validateNIF (value)
                    break;
                case NIE:
                    result = validateNIE (value)
                    break;
                case PASSPORT:
                    result = validatePassport (value)
                    break;
            }

            if (!result) {
                println "type " + type
                println "value " + value
            }
        }
        return result;
    }
}