Skip to content

Instantly share code, notes, and snippets.

@glaucocustodio
Last active February 4, 2016 17:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save glaucocustodio/f9664bbc43517ce614cc to your computer and use it in GitHub Desktop.
Save glaucocustodio/f9664bbc43517ce614cc to your computer and use it in GitHub Desktop.
Swift (1.2) function to validate CNPJ
// Returns true if the given cnpj is valid
func checkIfCNPJIsValid(cnpj: String) -> Bool {
if(cnpj.isEmpty) {
return true
}
// validates format, allowed ones: 38.041.242/0001-04, 38041242000104
var formatRegex = NSRegularExpression(pattern: "^[0-9\\.\\-\\/]*[0-9]$", options: NSRegularExpressionOptions.CaseInsensitive, error: nil)
if(formatRegex!.matchesInString(cnpj, options: nil, range:NSMakeRange(0, count(cnpj))).count == 0) {
return false
}
// remove any character that is not a decimal digit
var regex: NSRegularExpression = NSRegularExpression(pattern: "\\D", options: NSRegularExpressionOptions.CaseInsensitive, error: nil)!
var cnpj = regex.stringByReplacingMatchesInString(cnpj, options: nil, range: NSMakeRange(0, count(cnpj)), withTemplate: "")
if(cnpj == "") {
return false
}
if (count(cnpj) != 14) {
return false
}
// Elimina CNPJs invalidos conhecidos
if (cnpj == "00000000000000" ||
cnpj == "11111111111111" ||
cnpj == "22222222222222" ||
cnpj == "33333333333333" ||
cnpj == "44444444444444" ||
cnpj == "55555555555555" ||
cnpj == "66666666666666" ||
cnpj == "77777777777777" ||
cnpj == "88888888888888" ||
cnpj == "99999999999999") {
return false
}
// Valida DVs
var tamanho = count(cnpj) - 2
var numeros = (cnpj as NSString).substringWithRange(NSRange(location: 0, length: tamanho))
var digitos = (cnpj as NSString).substringWithRange(NSRange(location: count(cnpj)-2, length: 2))
var soma = 0;
var pos = tamanho - 7;
for (var i = tamanho; i >= 1; --i) {
var aux = String(Array(numeros)[tamanho-i]).toInt()! * pos--
soma += aux
if (pos < 2) {
pos = 9
}
}
var resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
if ("\(resultado)" != (digitos as NSString).substringWithRange(NSRange(location: 0, length: 1))) {
return false
}
tamanho = tamanho + 1;
numeros = (cnpj as NSString).substringWithRange(NSRange(location: 0, length: tamanho))
soma = 0;
pos = tamanho - 7;
for (var i = tamanho; i >= 1; --i) {
var aux = String(Array(numeros)[tamanho-i]).toInt()! * pos--
soma += aux
if (pos < 2) {
pos = 9
}
}
resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
if ("\(resultado)" != (digitos as NSString).substringWithRange(NSRange(location: 1, length: 1))) {
return false
}
return true
}
validarCNPJ("54.425.507/0001-16")
// true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment