Páginas

sexta-feira, 15 de junho de 2012

Validador de CPF em JAVA

Pessoal,

Após muito tempo sem postar, segue uma classe que acabei de fazer para uma aplicação, eu já havia utilizado ela em PHP, ela veio num plugin do Symfony Framework, e como achei magnificamente simples e útil segue a Implementação JAVA.

Vale passar os créditos da matemática para Rafael Goulart, autor da soma para o PHP.


/**
 * Copyright \copyright{} 2012 Hugo Prudente.
  
  Permission is granted to copy, distribute and/or modify this document
  under the terms of the GNU Free Documentation License, Version 1.3
  or any later version published by the Free Software Foundation;
  with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.
  A copy of the license is included in the section entitled ``GNU
  Free Documentation License''.

* É dada permissão para copiar, distribuir e / ou modificar este documento
  nos termos da GNU Free Documentation License, Versão 1.3 ou qualquer versão
  posterior publicada pela Free Software Fundação;
  sem Seções Invariantes, Textos de Capa, e sem Textos de Quarta Capa. 
  Uma cópia da licença é incluída na seção intitulada ``GNU Free 
  Documentation License.''
 */

package br.com.magicorp.magi.validator;

import java.util.regex.Pattern;

/**
 *  Valida CPF de uma maneira simples e precisa.
 * 
 * 
 * @author Hugo Prudente
 */
public class CpfValidator {

  private static char[] aCpf;

  /**
   *  Valida um CPF, através de uma string recebida;
   * 
   * @param cpf
   * @return boolean
   */
  public static boolean validaCpf(String cpf) {
    cpf = cpf.replaceAll(Pattern.compile("\\s").toString(),"");
    cpf = cpf.replaceAll(Pattern.compile("\\D").toString(),"");

    int soma = 0;

    if (cpf.length() != 11) {
      return false;
    }

    aCpf = cpf.toCharArray();


    // Verifica 1º digito
    for (int i = 0; i < 9; i++) {
      int j = (i + 1);
      int x = Integer.parseInt(Character.toString(aCpf[i]));
      soma += ( j * x);     
    }

    int d1 = (soma % 11);
    if (d1 == 10) {
      d1 = 0;
    }

    // Verifica o 2º digito
    soma = 0;
    int j = 0;
    for (int i = 9 ; i > 0 ; i--){
      int x = Integer.parseInt(Character.toString(aCpf[j]));
      soma += (i * x);
      j++;
    }

    int d2 = (soma % 11);

    if (d2 == 10) {
      d2 = 0;
    }

    if (d1 == Integer.parseInt(Character.toString(aCpf[9])) 
        && 
        d2 == Integer.parseInt(Character.toString(aCpf[10]))
       ) {
      return true;
    } else {
      return false;
    }
  }
}

Nenhum comentário:

Postar um comentário