sexta-feira, 17 de setembro de 2010

Validação de CPF e CNPJ em Flex

A classe Validator é feita para validar campos em Flex. Apesar de existir vários validadores por padrão, como de cartão de crédito e mail, não existem os de CPF e CNPJ. Fiz um validador para as duas, ambas com teste unitário:

 CNPJ:


package br.com.nuccitelli.validator {
     import mx.utils.ObjectUtil;
     import mx.validators.ValidationResult;
     import mx.validators.Validator;

     public class CNPJValidator extends Validator {
         static protected const FIRST_VERIFIER_DIGITS:Array=[ 5,4,3,2,9,8,7,6,5,4,3,2 ];
         static protected const SECOND_VERIFIER_DIGITS:Array=[ 6,5,4,3,2,9,8,7,6,5,4,3 ];

         override protected function doValidation(value:Object):Array {
              var results:Array=[];
              // Call base class doValidation().
              results=super.doValidation(value);
              // Return if there are errors.
              if(results.length>0)
                   return results;
              // Check first name field.
              var cnpj:String=value as String;
              if(cnpj==null||cnpj=="") {
                   return results;
              } else if(cnpj.length!=14) {
                   results.push(new ValidationResult(true,"","","O CNPJ deve conter 14 dígitos"));
                   return results;
              } else if(!verifyDigits(cnpj)) {
                   results.push(new ValidationResult(true,"","","CNPJ inválido"));
                   return results;
              }
              return results;
         }

         private function verifyDigits(cnpj:String):Boolean {
              var firstDigit:int=defineDigitValue(getDigitsPlusOperation(cnpj,FIRST_VERIFIER_DIGITS)%11);
              if(new Number(firstDigit)!=new Number(cnpj.charAt(12))) {
                   return false;
              }
              var secondDigit:int=defineDigitValue((getDigitsPlusOperation(cnpj,SECOND_VERIFIER_DIGITS)+firstDigit*2)%11);
              return new Number(secondDigit)==new Number(cnpj.charAt(13));
         }

         private function defineDigitValue(digit:int):int {
              return digit>1?11-digit:0;
         }

         private function getDigitsPlusOperation(cnpj:String,verifierDigitis:Array):int {
              var s:int=0;
              for(var i:int=0;i<12;++i) {
                   s+=new Number(cnpj.charAt(i))*verifierDigitis[i];
              }
              return s;
         }
     }
}

Teste do CNPJ:

package br.com.nuccitelli.validator {
     import flexunit.framework.Assert;
     import mx.validators.ValidationResult;

     public class CNPJValidatorTest {
         protected var cnpjValidator:CNPJValidator=new CNPJValidator();

         [Test]
         public function testValidCNPJ():void {
              Assert.assertNull(cnpjValidator.validate("11222333000181").results);
         }

         [Test]
         public function testUncompleteCNPJ():void {
              Assert.assertEquals("O CNPJ deve conter 14 dígitos",getValidationMessage(cnpjValidator.validate("1").results[0] as ValidationResult));
              Assert.assertEquals("O CNPJ deve conter 14 dígitos",getValidationMessage(cnpjValidator.validate("1212").results[0] as ValidationResult));
              Assert.assertEquals("O CNPJ deve conter 14 dígitos",getValidationMessage(cnpjValidator.validate("1122233300018").results[0] as ValidationResult));
         }

         [Test]
         public function testWrongFinalDigits():void {
              Assert.assertEquals("CNPJ inválido",getValidationMessage(cnpjValidator.validate("11222333000180").results[0] as ValidationResult));
              Assert.assertEquals("CNPJ inválido",getValidationMessage(cnpjValidator.validate("11222333000191").results[0] as ValidationResult));
              Assert.assertEquals("CNPJ inválido",getValidationMessage(cnpjValidator.validate("11222333000190").results[0] as ValidationResult));
         }

         private function getValidationMessage(result:ValidationResult):String {
              return result.errorMessage;
         }
     }
}


CPF:

package br.com.nuccitelli.validator {
     import mx.utils.ObjectUtil;
     import mx.validators.ValidationResult;
     import mx.validators.Validator;

     public class CPFValidator extends Validator {
         override protected function doValidation(value:Object):Array {
              var results:Array=[];
              // Call base class doValidation().
              results=super.doValidation(value);
              // Return if there are errors.
              if(results.length>0)
                   return results;
              // Check first name field.
              var cpf:String=value as String;
              if(cpf==null||cpf=="") {
                   return results;
              } else if(cpf.length!=11) {
                   results.push(new ValidationResult(true,"","","O CPF deve conter 11 dígitos"));
                   return results;
              } else if(!verifyDigits(cpf)) {
                   results.push(new ValidationResult(true,"","","CPF inválido"));
                   return results;
              }
              return results;
         }

         private function verifyDigits(cpf:String):Boolean {
              var firstDigit:int=defineDigitValue(getDigitsPlusOperation(cpf,10)%11);
              if(new Number(firstDigit)!=new Number(cpf.charAt(9))) {
                   return false;
              }
              var secondDigit:int=defineDigitValue((getDigitsPlusOperation(cpf,11)+firstDigit*2)%11);
              return new Number(secondDigit)==new Number(cpf.charAt(10));
         }

         private function defineDigitValue(digit:int):int {
              return digit>1?11-digit:0;
         }

         private function getDigitsPlusOperation(cpf:String,initialFactor:int):int {
              var s:int=0;
              for(var i:int=0;i<9;++i,--initialFactor) {
                   s+=new Number(cpf.charAt(i))*initialFactor;
              }
              return s;
         }
     }
}


Teste do CPF:

package br.com.nuccitelli.validator {
     import flexunit.framework.Assert;
     import mx.validators.ValidationResult;

     public class CPFValidatorTest {
         protected var cpfValidator:CPFValidator=new CPFValidator();

         [Test]
         public function testValidCPF():void {
              Assert.assertNull(cpfValidator.validate("12345678909").results);
         }

         [Test]
         public function testUncompleteCPF():void {
              Assert.assertEquals("O CPF deve conter 11 dígitos",getValidationMessage(cpfValidator.validate("1").results[0] as ValidationResult));
              Assert.assertEquals("O CPF deve conter 11 dígitos",getValidationMessage(cpfValidator.validate("1212").results[0] as ValidationResult));
              Assert.assertEquals("O CPF deve conter 11 dígitos",getValidationMessage(cpfValidator.validate("1234567890").results[0] as ValidationResult));
         }

         [Test]
         public function testWrongFinalDigits():void {
              Assert.assertEquals("CPF inválido",getValidationMessage(cpfValidator.validate("12345678919").results[0] as ValidationResult));
              Assert.assertEquals("CPF inválido",getValidationMessage(cpfValidator.validate("12345678908").results[0] as ValidationResult));
              Assert.assertEquals("CPF inválido",getValidationMessage(cpfValidator.validate("12345678918").results[0] as ValidationResult));
         }

         private function getValidationMessage(result:ValidationResult):String {
              return result.errorMessage;
         }
     }
}



Espero que economize tempo do pessoal :)

Nenhum comentário: