Committed by
GitHub
Merge pull request #356 from kauemurakami/isCpf
adding function to validate cpf isCpf
Showing
1 changed file
with
41 additions
and
0 deletions
@@ -293,6 +293,47 @@ class GetUtils { | @@ -293,6 +293,47 @@ class GetUtils { | ||
293 | /// Checks if num a EQUAL than num b. | 293 | /// Checks if num a EQUAL than num b. |
294 | static bool isEqual(num a, num b) => a == b; | 294 | static bool isEqual(num a, num b) => a == b; |
295 | 295 | ||
296 | + /// Checks if the cpf is valid. | ||
297 | + static bool isCpf(String cpf) { | ||
298 | + if (cpf == null) return false; | ||
299 | + | ||
300 | + // get only the numbers | ||
301 | + var numbers = cpf.replaceAll(RegExp(r'[^0-9]'), ''); | ||
302 | + // Test if the CPF has 11 digits | ||
303 | + if (numbers.length != 11) return false; | ||
304 | + // Test if all CPF digits are the same | ||
305 | + if (RegExp(r'^(\d)\1*$').hasMatch(numbers)) return false; | ||
306 | + | ||
307 | + // split the digits | ||
308 | + List<int> digits = | ||
309 | + numbers.split('').map((String d) => int.parse(d)).toList(); | ||
310 | + | ||
311 | + // Calculate the first verifier digit | ||
312 | + var calcDv1 = 0; | ||
313 | + for (var i in Iterable<int>.generate(9, (i) => 10 - i)) { | ||
314 | + calcDv1 += digits[10 - i] * i; | ||
315 | + } | ||
316 | + calcDv1 %= 11; | ||
317 | + var dv1 = calcDv1 < 2 ? 0 : 11 - calcDv1; | ||
318 | + | ||
319 | + // Tests the first verifier digit | ||
320 | + if (digits[9] != dv1) return false; | ||
321 | + | ||
322 | + // Calculate the second verifier digit | ||
323 | + var calcDv2 = 0; | ||
324 | + for (var i in Iterable<int>.generate(10, (i) => 11 - i)) { | ||
325 | + calcDv2 += digits[11 - i] * i; | ||
326 | + } | ||
327 | + calcDv2 %= 11; | ||
328 | + | ||
329 | + var dv2 = calcDv2 < 2 ? 0 : 11 - calcDv2; | ||
330 | + | ||
331 | + // Test the second verifier digit | ||
332 | + if (digits[10] != dv2) return false; | ||
333 | + | ||
334 | + return true; | ||
335 | + } | ||
336 | + | ||
296 | /// Capitalize each word inside string | 337 | /// Capitalize each word inside string |
297 | /// Example: your name => Your Name, your name => Your name | 338 | /// Example: your name => Your Name, your name => Your name |
298 | /// | 339 | /// |
-
Please register or login to post a comment