Javascript NIF/CIF/NIE


/ Published in: JavaScript
Save to your folder(s)



Copy this code and paste it in your HTML
  1. function validate_nif( cif ) {
  2. // Based on php function of David Vidal Serra.
  3. //Returns: 1 = NIF ok, 2 = CIF ok, 3 = NIE ok, -1 = NIF bad, -2 = CIF bad, -3 = NIE bad, 0 = ??? bad
  4. // cif = inpt.value;
  5. num = new Array();
  6. cif = cif.toUpperCase();
  7. for (i = 0; i < 9; i ++) {
  8. num[i] = cif.substr(i, 1);
  9. }
  10. //si no tiene un formato valido devuelve error
  11. if (!cif.match('((^[A-Z]{1}[0-9]{7}[A-Z0-9]{1}$|^[T]{1}[A-Z0-9]{8}$)|^[0-9]{8}[A-Z]{1}$)')) {
  12. return 0;
  13. }
  14. //comprobacion de NIFs estandar
  15. if (cif.match('(^[0-9]{8}[A-Z]{1}$)')){
  16. if (num[8] == 'TRWAGMYFPDXBNJZSQVHLCKE'.substr(cif.substr(0, 8) % 23, 1)){
  17. return 1;
  18. } else {
  19. return -1;
  20. }
  21. }
  22. //algoritmo para comprobacion de codigos tipo CIF
  23. suma = num[2] + num[4] + num[6];
  24. for (i = 1; i < 8; i += 2) {
  25. suma += toString((2 * num[i])).substr(0,1) + toString((2 * num[i])).substr(1,1);
  26. }
  27. n = 10 - suma.substr( suma.length - 1, 1);
  28. //comprobacion de NIFs especiales (se calculan como CIFs)
  29. if (cif.match('^[KLM]{1}')) {
  30. if (num[8] == String.fromCharCode(64 + n)){
  31. return 1;
  32. } else {
  33. return -1;
  34. }
  35. }
  36. //comprobacion de CIFs
  37. if (cif.match('^[ABCDEFGHJNPQRSUVW]{1}')) {
  38. if (num[8] == String.fromCharCode(64 + n) || num[8] == n.substr(n.length - 1, 1)) {
  39. return 2;
  40. } else {
  41. return -2;
  42. }
  43. }
  44. //comprobacion de NIEs
  45. //T
  46. if (cif.match('^[T]{1}')) {
  47. if (num[8] == cif.match('^[T]{1}[A-Z0-9]{8}$')) {
  48. return 3;
  49. } else {
  50. return -3;
  51. }
  52. }
  53. //XYZ
  54. if (cif.match('^[XYZ]{1}')) {
  55. tmpstr = cif.replace('X', '0');
  56. tmpstr = tmpstr.replace('Y', '1');
  57. tmpstr = tmpstr.replace('Z', '2');
  58. if (num[8] == 'TRWAGMYFPDXBNJZSQVHLCKE'.substr( tmpstr.substr(0, 8) % 23, 1)) {
  59. return 3;
  60. } else {
  61. return -3;
  62. }
  63. }
  64. //si todavia no se ha verificado devuelve error
  65. return 0;
  66.  
  67. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.