Skip to content

Instantly share code, notes, and snippets.

@vitoo
Last active November 17, 2021 16:13
Show Gist options
  • Save vitoo/7e5360c66a68a2836f67ff41ac892f4b to your computer and use it in GitHub Desktop.
Save vitoo/7e5360c66a68a2836f67ff41ac892f4b to your computer and use it in GitHub Desktop.
Generate DNI/NIF for Spain and Portugal, in javascript
//credit : https://github.com/asmarques/pt-id
function pad(value, length) {
var result = value + '';
while (result.length < length) {
result = '0' + result;
}
return result;
}
function checkDigit(value) {
var sum = 0;
var len = value.length;
for (var i = 0; i < len; i++) {
sum += value[i] * (len + 1 - i);
}
var mod = sum % 11;
return '' + ((mod === 0 || mod === 1) ? 0 : 11 - mod);
}
function generate(prefix) {
var value = pad(Math.floor(Math.random() * 99999999), 8);
if (prefix) {
value = prefix + value.slice(prefix.length, value.length);
}
return value + checkDigit(value);
}
// personal = 1,2,3
//company = 5
generate('1');
//credit : https://gist.github.com/THuRStoN/9468324
function formatNumberLength(num, length) {
var r = "" + num;
while ( r.length < length ) {
r = "0" + r;
}
return r;
}
function charDNI(dni) {
var chain = "TRWAGMYFPDXBNJZSQVHLCKET";
var pos = dni % 23;
var letter = chain.substring( pos, pos + 1 );
return letter;
}
function rand_dni() {
num = Math.floor( ( Math.random() * 100000000 ) );
sNum = formatNumberLength( num, 8 );
return sNum + charDNI( sNum );
}
rand_dni();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment