function isValidNif(a){
ovar temp=a.toUpperCase();
ovar cadenadni="TRWAGMYFPDXBNJZSQVHLCKE";
oif (temp!==''){
oif ((!/^[A-Z]{1}[0-9]{7}[A-Z0-9]{1}$/.test(temp) && !/^[T]{1}[A-Z0-9]{8}$/.test(temp)) && !/^[0-9]{8}[A-Z]{1}$/.test(temp)){
oreturn 0;
o}
oif (/^[0-9]{8}[A-Z]{1}$/.test(temp)){
oposicion = a.substring(8,0) % 23;
oletra = cadenadni.charAt(posicion);
ovar letradni=temp.charAt(8);
oif (letra == letradni){
o return 1;
o}else{
oreturn -1;
o}
o}
osuma = parseInt(a[2])+parseInt(a[4])+parseInt(a[6]);
ofor (i = 1; i < 8; i += 2){
otemp1 = 2 * parseInt(a[i]);
otemp1 += '';
otemp1 = temp1.substring(0,1);
otemp2 = 2 * parseInt(a[i]);
otemp2 += '';
otemp2 = temp2.substring(1,2);
oif (temp2 == ''){
otemp2 = '0';
o}
osuma += (parseInt(temp1) + parseInt(temp2));
o}
osuma += '';
on = 10 - parseInt(suma.substring(suma.length-1, suma.length));
oif (/^[KLM]{1}/.test(temp)){
oif (a[8] == String.fromCharCode(64 + n)){
oreturn 1;
o}else{
oreturn -1;
o}
o}
oif (/^[ABCDEFGHJNPQRSUVW]{1}/.test(temp)){
otemp = n + '';
oif (a[8] == String.fromCharCode(64 + n) || a[8] == parseInt(temp.substring(temp.length-1, temp.length))){
oreturn 2;
o}else{
oreturn -2;
o}
o}
o//comprobacion de NIEs
o//T
oif (/^[T]{1}/.test(temp)){
oif (a[8] == /^[T]{1}[A-Z0-9]{8}$/.test(temp)){
oreturn 3;
o}else{
oreturn -3;
o}
o}
oif (/^[XYZ]{1}/.test(temp)){
opos = str_replace(['X', 'Y', 'Z'], ['0','1','2'], temp).substring(0, 8) % 23;
oif (a[8] == cadenadni.substring(pos, pos + 1)){
oreturn 3;
o}else{
oreturn -3;
o}
o}
o}
oreturn 0;
}
Necesitaremos también la siguiente función que emula a str_replace de php
function str_replace(search, replace, subject) {
var f = search, r = replace, s = subject;
var ra = r instanceof Array, sa = s instanceof Array, f = [].concat(f), r = [].concat(r), i = (s = [].concat(s)).length;
while (j = 0, i--) {
if (s[i]) {
while (s[i] = s[i].split(f[j]).join(ra ? r[j] || "" : r[0]), ++j in f){};
}
};
return sa ? s : s[0];
}
