Skip to content

Instantly share code, notes, and snippets.

@eaguad1337
Created October 16, 2017 20:43
Show Gist options
  • Save eaguad1337/9bcdb88cc36b2effeeb2614c9a006471 to your computer and use it in GitHub Desktop.
Save eaguad1337/9bcdb88cc36b2effeeb2614c9a006471 to your computer and use it in GitHub Desktop.
Chilean Rut Validator for VeeValidate
// Eduardo Aguad [email protected]
// Use:
// yarn add vee-validate
// import VeeValidate, {Validator} from 'vee-validate';
// Validator.extend('rut', require('./VeeRutValidator'));
// <input type="text" name="rut" v-validate="rut">
module.exports = {
getMessage: (field, params, data) => `El campo ${field} no es un rut válido`,
validate: rut => {
if (typeof(rut) !== 'string') {
return false;
}
var cRut = rut.replace(/[\.-]/g, '');
var cDv = cRut.charAt(cRut.length - 1).toUpperCase();
var nRut = parseInt(cRut.substr(0, cRut.length - 1));
if (isNaN(nRut)) {
return false;
}
var sum = 0;
var factor = 2;
nRut = nRut.toString();
for (var i = nRut.length - 1; i >= 0; i--) {
sum = sum + nRut.charAt(i) * factor;
factor = (factor + 1) % 8 || 2;
}
let computedDv = 0;
switch (sum % 11) {
case 1:
computedDv = 'k';
break;
case 0:
computedDv = 0;
break;
default:
computedDv = 11 - (sum % 11);
break;
}
return computedDv.toString().toUpperCase() === cDv.toString().toUpperCase();
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment