Skip to content

Instantly share code, notes, and snippets.

@matiaslopezd
Last active February 27, 2021 18:33
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save matiaslopezd/08968f8421aa88c1ba1b7e631e348836 to your computer and use it in GitHub Desktop.
Save matiaslopezd/08968f8421aa88c1ba1b7e631e348836 to your computer and use it in GitHub Desktop.
Chilean DNI validator and get in JSON { run: Number/String, adv: Number/String, dv: Number/String, valid: Boolean }
function DNI_CL({ run, string }){
if(run !== '' && (typeof run === "string" || typeof run === "number")){
function format(n){
if (typeof n === 'string') {
// Remove '.' if exist
n = (n.includes('.')) ? n.split('.').join('') : n;
// Remove '-' if exist
n = (n.includes('-')) ? n.split('-').join('') : n;
}
return n;
}
function DV(n){
// Initialize multiples and total
let m = 2, sum = 0;
// Reverse string
n = n.split('').reverse().join('');
// Algorithm to get the DV
n.split('').map((i) => {
// Multiply digit by multiples [2,7]
sum += (Number(i) * m);
// Add one to mutiple variable
m = (m < 7) ? m+1 : 2;
});
// Get remainder of the division and after get subtraction
const dv = (11 - (sum % 11));
return (dv === 10) ? 'K' : (dv === 11) ? 0 : dv ;
}
function formatter({run, dv}){
// Get the first numbers
const a1 = run.slice(0, run.length - 6);
// Get the last 6 numbrs
const a2 = run.slice(run.length - 6, run.length).match(/.{1,3}/g).join('.');
// Return in string or number format
return (string) ? ((dv) ? `${a1}.${a2}-${DV(run)}` : `${a1}.${a2}`) : ((dv && typeof DV(run) === "number") ? Number(`${run}${DV(run)}`) : Number(run));
}
run = format(run);
// Get DV
let dv = run.toString().split('')[run.toString().split('').length - 1];
// If is number convert or set to uppercase
dv = (Number(dv)) ? Number(dv) : dv.toUpperCase();
// Format and remove the last number
run = run.toString().slice(0, -1);
// Return JSON format
return {
run: formatter({run, dv: true}),
adv: formatter({run}),
dv: (string) ? DV(run).toString() : DV(run),
valid: (DV(run).toString() === dv.toString())
}
} else {
return { run: 0, adv: 0, dv: 0, valid: false };
}
}
function DNI_CL({run,string}){if(run!==''&&(typeof run==="string"||typeof run==="number")){function format(n){if(typeof n==='string'){n=(n.includes('.'))?n.split('.').join(''):n;n=(n.includes('-'))?n.split('-').join(''):n}
return n}
function DV(n){let m=2,sum=0;n=n.split('').reverse().join('');n.split('').map((i)=>{sum+=(Number(i)*m);m=(m<7)?m+1:2});const dv=(11-(sum%11));return(dv===10)?'K':(dv===11)?0:dv}
function formatter({run,dv}){const a1=run.slice(0,run.length-6);const a2=run.slice(run.length-6,run.length).match(/.{1,3}/g).join('.');return(string)?((dv)?`${a1}.${a2}-${DV(run)}`:`${a1}.${a2}`):((dv&&typeof DV(run)==="number")?Number(`${run}${DV(run)}`):Number(run))}
run=format(run);let dv=run.toString().split('')[run.toString().split('').length-1];dv=(Number(dv))?Number(dv):dv.toUpperCase();run=run.toString().slice(0,-1);return{run:formatter({run,dv:!0}),adv:formatter({run}),dv:(string)?DV(run).toString():DV(run),valid:(DV(run).toString()===dv.toString())}}else{return{run:0,adv:0,dv:0,valid:!1}}}
@matiaslopezd
Copy link
Author

matiaslopezd commented May 21, 2019

Demo / Ejemplo

Codepen demo

How to use

This is a very simple function for get the validation of Chilean DNI. For use only need configurate { run } key that is the DNI and can be in string or number, also can choose output DNI in string or number format in { string } key.

The output returns run DNI formated based in string key configuration (true/false), avd are the numbers before verifier digit, dv is the verifier digit and finally valid is boolean indicate is valid or not.

// Example 1
DNI_CL({ run: '111111111', string: true });
// Output
{run: '11.111.111-1', adv: '11.111.111', dv: '1', valid: true}

// Example 2
DNI_CL({ run: '1.111.111-1' });
// Output
{run: 11111114, adv: 1111111, dv: 4, valid: false}

// Example 3
DNI_CL({ run: '' }); // DNI_CL({ });
// Output
{run: 0, adv: 0, dv: 0, valid: false}

Como usar

Esta es una función muy simple para validar el RUT/RUN. Para empezar necesitamos configurar { run } que es el RUT/RUN y puede ser en string o number, también es posible configurar la salida del RUT en string o number en { string }.

La salida se compone de run que es el RUT/RUN formateado basado en la key string, avd son los números anteriores al dígito verificador, dv es el dígito verificador y finalmente valid es un boolean que indica la validez.

// Ejemplo 1
DNI_CL({ run: '111111111', string: true });
// Salida
{run: '11.111.111-1', adv: '11.111.111', dv: '1', valid: true}

// Ejemplo 2
DNI_CL({ run: '1.111.111-1' });
// Salida
{run: 11111114, adv: 1111111, dv: 4, valid: false}

// Ejemplo 3
DNI_CL({ run: '' }); // DNI_CL({ });
// Output
{run: 0, adv: 0, dv: 0, valid: false}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment