Block expired dates in an input type date

2

How can I block previous dates in an input type date

    
asked by Raul 01.08.2016 в 17:31
source

4 answers

6

Use the min attribute:

<input type="date" min="2016-01-01">

Here is some documentation: link

    
answered by 01.08.2016 в 17:40
5

In HTML5 there is the attribute min , unfortunately HTML5 has no way to get the current date to put it as value of an attribute.

Possible solutions:

PHP:

<input type="date" name="fecha" id="fecha" placeholder="Introduce una fecha" required min=<?php $hoy=date("Y-m-d"); echo $hoy;?> />

Javascript:

document.getElementById('#fecha').value = new Date().toDateInputValue();

Javascript with jQuery's help:

 $(document).ready( function() {
    $('#fecha').val(new Date().toDateInputValue());
});​
    
answered by 01.08.2016 в 19:06
1

If you want to validate it on the server side (PHP) use the following:

    $fechaEntrada = '2016-07-22';
    $fechaLimite = '2016-08-01';
//si la fecha enviada del form es menor a la que deseas validar
        if( strtotime($fecha_entrada) < strtotime($fecha_limite) ) {
        //la fecha es menor
        }else{
        //la operación fue realizada en un periodo válido
        }

To validate it in JS you can do the following:

var fechaEntrada = '2016-07-22';
var fechaLimite = '2016-08-01';
if( (new Date(fechaEntrada).getTime() < new Date(fechaLimite).getTime()))
{
   //alert('la fecha es menor'); 
    //return false;
}else{
 //return true;
}
    
answered by 01.08.2016 в 18:44
0

I had the same question, but using java script you can solve it in simple way

First remember that you must have the min attribute enabled in your input

<input type="date" id="fechaReserva" min="2017-01-01" />

Then use this function by replacing the id exactly

    var fecha = new Date();
    var anio = fecha.getFullYear();
    var dia = fecha.getDate();
    var _mes = fecha.getMonth();//viene con valores de 0 al 11
    _mes = _mes + 1;//ahora lo tienes de 1 al 12
    if (_mes < 10)//ahora le agregas un 0 para el formato date
    { var mes = "0" + _mes;}
    else
    { var mes = _mes.toString;}
    document.getElementById("fechaReserva").min = anio+'-'+mes+'-'+dia; 
    
answered by 23.06.2017 в 22:46