Validate day - Javascript - DOM [duplicate]

0

I have an input of type text with a length = 2.

<input type="text" size="4" maxlength="2" name="dia" id="iddia"/>

Where I want to validate that what is written are only numbers and that if I write a number greater than or equal to 4, then I can not write more numbers because the day 45-66-81 does not exist, and if I write the first digit on 3, just allow me the values 30-31.

Why can I write any number from 1 to 99?

//Validar el dia.
function validacionDia(e){
    var key = e.which || e.keyCode;
    var value = document.getElementById("iddia").value;
    var dia = value + String.fromCharCode(key);
    if (isNaN(dia) === true || dia < 1 || dia > 31) {
        return false;
    }
    return true;
}

miformulario.dia.addEventListener("change", function(){ 
        return validacionDia(event);
    }, false);

And for the validation of a year / birth? Accept values between 1960 and 2010

//Validar el año.
function validacionAnio(e){
    var key = e.which || e.keyCode;
    var value = document.getElementById("idanio").value;
    var anio = value + String.fromCharCode(key);
    return (anio>0 && anio<2010);
} 
    
asked by omaza1990 17.05.2017 в 11:07
source

1 answer

1

Here I leave the code, I hope it serves you

function validaDia(value) {

  var valueInt = parseInt(value);
  if (isNaN(value)) {
    document.getElementById('iddia').value = '';
  } else if (value.length == 1 && valueInt >= 4) {
    document.getElementById('iddia').value = '0' + value;
  } else if (value.length == 2 && parseInt(value.substring(0, 1)) == 3 && (parseInt(value.substring(1, 2)) != 0 && parseInt(value.substring(1, 2)) != 1)) {
    document.getElementById('iddia').value = 3;
  }
}

function validacionAnio(val){
    if(val.length==4 && !val.match('(19[6-8][0-9]|199[0-9]|200[0-9]|2010)')){
        document.getElementById('idanio').value='';
    }
} 

document.getElementById('iddia').addEventListener("keyup", function(evt) {
  validaDia(this.value);
}, false);

document.getElementById('idanio').addEventListener("keyup", function(evt) {
  validacionAnio(this.value);
}, false);

I used the onKeyUp event, since text-type input does not have an onChange event

    
answered by 17.05.2017 / 11:32
source