JSFiddle - React, Tailwind, and code Playground
by _cronos2
HTML
<body>
<input type="text" id="input" value="" placeholder="83730219*" />
<input type="button" id="button" value="Calcular DNI" />
<br /><br />
<input type="text" id="output" disabled value="83730219F" />
</body>
CSS
body {
margin:20px;
}
#button {
margin-left:5px;
padding:3px 5px;
background:#CCC;
border:3px solid #CCC;
border-radius:3px;
cursor:pointer;
}
#button:hover {
background:white;
}
input {
border:1px solid #CCC;
border-radius:2px;
padding:3px;
}
JavaScript
var DNI = function(digits, letter){
this.digits = '';
this.letter = '';
if( !DNI.checkDNI(digits + letter) ){ return false; }
if(digits){ this.digits = digits; }
if(letter){ this.letter = letter; }
}
DNI.checkDNI = function(str){
return /^\d*\*?\d*(\*?|[A-Z])$/i.test(str)
&& str.length == 9;
}
DNI.letters = ["T", "R", "W", "A", "G", "M", "Y", "F", "P", "D", "X", "B", "N", "J", "Z", "S", "Q", "V", "H", "L", "C", "K", "E"];
DNI.prototype.calcLetter = function(){
return DNI.letters[ +this.digits % 23 ];
}
DNI.prototype.calcNumber = function(){
for(var i = 0; i < 10; i++){
var digits = +this.digits.replace('*', i);
if( DNI.letters[ digits % 23 ] == this.letter ){
return digits;
}
}
return false;
}
DNI.prototype.complete = function(){
if( DNI.checkDNI( this.toString() ) ){
if(this.letter == '*'){
return this.digits + this.calcLetter();
} else {
if( !this.calcNumber() ){ return false; }
return this.calcNumber() + this.letter;
}
}
return false;
}
DNI.prototype.toString = function(){
return this.digits + this.letter;
}
$('#button').on('click', function(){
var input = $('#input'), output = $('#output');
var val = input.val();
var dni = new DNI(
val.substr(0, 8), val.substr(8)
);
var complete = dni.complete();
if( DNI.checkDNI( dni.toString() ) && complete ){
output.val( complete );
} else {
alert('Error, introduzca un DNI válido');
return false;
}
});