Created
December 28, 2018 18:56
-
-
Save alvaaz/f97db1bbe6cc8121234c591077359925 to your computer and use it in GitHub Desktop.
Validar RUT Vanilla JS
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
| //Validar rut | |
| function cleanRut(_value) { | |
| return typeof _value === 'string' ? _value.replace(/[^0-9kK]+/g,'').toUpperCase() : ''; | |
| } | |
| function formatRut(_value, _default) { | |
| _value = cleanRut(_value); | |
| if(!_value) return _default; | |
| if(_value.length <= 1) return _value; | |
| var result = _value.slice(-4,-1) + '-' + _value.substr(_value.length-1); | |
| for(var i = 4; i < _value.length; i+=3) result = _value.slice(-3-i,-i) + '.' + result; | |
| return result; | |
| } | |
| function validateRut(_value) { | |
| if(typeof _value !== 'string') return false; | |
| var t = parseInt(_value.slice(0,-1), 10), m = 0, s = 1; | |
| while(t > 0) { | |
| s = (s + t%10 * (9 - m++%6)) % 11; | |
| t = Math.floor(t / 10); | |
| } | |
| var v = (s > 0) ? (s-1)+'' : 'K'; | |
| return (v === _value.slice(-1)); | |
| } | |
| if(document.getElementById("rut")) { | |
| document.getElementById("rut").addEventListener("keyup", (e) => { | |
| if(e.target.value.length > 12) { | |
| e.target.value = e.target.value.substring(0, e.target.value.length - 1); | |
| } | |
| e.target.value = formatRut(cleanRut(e.target.value)) || ""; | |
| }) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment