Last active
October 7, 2020 20:08
-
-
Save aatronco/9b54876b87f12332b6e2dcc6a6fb7fe8 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<script> | |
$(document).ready(function(){ | |
addRutValidator($('#order_shipping_address_taxid')); | |
addRutValidatorForBillingAddress($('#order_billing_address_taxid')); | |
$("#shipping_same_as_billing").on('change', function(evt) { | |
addRutValidatorForBillingAddress($('#order_billing_address_taxid')); | |
}) | |
}) | |
function addRutValidatorForBillingAddress(element) { | |
if($("#shipping_same_as_billing:checked").val() == 1){ | |
element.prop('required', false); | |
element.unbind('keyup', checkRut); | |
$('#order_billing_address_municipality').prop('required', false); | |
} | |
else { | |
$('#order_billing_address_municipality').prop('required', true); | |
addRutValidator(element); | |
} | |
} | |
function addRutValidator(element) { | |
element.prop('required', true); | |
element.bind('keyup', checkRut) | |
} | |
function checkRut(evt) { | |
var rut = evt.currentTarget | |
// remove dots | |
var value = rut.value.replace('.', ''); | |
// remove dash | |
value = value.replace('-', ''); | |
// isolate rutBody and Dígito Verificador | |
rutBody = value.slice(0, -1); | |
digit = value.slice(-1).toUpperCase(); | |
// Format RUN | |
rut.value = rutBody + '-'+ digit; | |
// Si no cumple con el mínimo ej. (n.nnn.nnn) | |
if(rutBody.length < 7) { | |
rut.setCustomValidity("RUT Incompleto"); | |
return false; | |
} | |
// calculate digit verifier | |
digitsSum = 0; | |
multiplier = 2; | |
// for each digit on rutBody | |
for (i=1; i <= rutBody.length; i++) { | |
// get product of corresponding multiplier | |
index = multiplier * value.charAt(rutBody.length - i); | |
// add digt sum to counter | |
digitsSum = digitsSum + index; | |
if (multiplier < 7) { | |
multiplier = multiplier + 1; | |
} else { | |
multiplier = 2; | |
} | |
} | |
// calculate digitVerifier on base module 11 | |
digitVerifier = 11 - (digitsSum % 11); | |
// special cases (0 and K) | |
digit = (digit == 'K')?10:digit; | |
digit = (digit == 0)?11:digit; | |
// validtes rutBody with his digit | |
if(digitVerifier != digit) { | |
rut.setCustomValidity("RUT Inválido"); | |
return false; | |
} | |
rut.setCustomValidity(''); | |
} | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment