Validate that date and time are not less than the current datetime-local input

1

I have a datetime-local type field in a form, and I need that the entered date and time are not lower than the current ones. Is it possible to do that? I tested with the min attribute of html5 and assigned the current date and time to avoid being entered without obtaining a good result. The field in the database is of a datetime. Is not it possible to do it using javascript, any example?

<div class="form-group">

 <label>Hrs y Fecha de Inicio</label>
 <input type="datetime-local" class="form-control" id="fecha_ini" name="fecha_ini" min="<?php localtime();?>">
</div>
    
asked by CristianOx21 03.10.2017 в 18:28
source

2 answers

1

To do it with PHP

$hoy             = date("Y-m-d");
$fechaFormulario = "2017-10-01";

// Si la fecha es de apartir de hoy => true 
if ($hoy <= $fechaFormulario) {

    echo "Fecha a partir de hoy";
}
else {

    echo "Debes selecionar una fecha mayor a Hoy";
}

To do it with javascript: (Not recommended)

var hoy             = new Date();
var fechaFormulario = new Date('2017-10-1');

// Comparamos solo las fechas => no las horas!!
hoy.setHours(0,0,0,0);  // Lo iniciamos a 00:00 horas

if (hoy <= fechaFormulario) {

  console.log("Fecha a partir de hoy");
}
else {
  console.log("Debes elegir una fecha mayor que hoy");
}

Validating a datetimepicker: (If you notice this, you do not give the user options to choose dates earlier than today)

var dateToday = new Date();
var dates = $("#from, #to").datepicker({
    defaultDate: "+1w",
    changeMonth: true,
    numberOfMonths: 3,
    minDate: dateToday,
    onSelect: function(selectedDate) {
        var option = this.id == "from" ? "minDate" : "maxDate",
            instance = $(this).data("datepicker"),
            date = $.datepicker.parseDate(instance.settings.dateFormat || $.datepicker._defaults.dateFormat, selectedDate, instance.settings);
        dates.not(this).datepicker("option", option, date);
    }
});
<link href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

<label for="from">From</label> <input type="text" id="from" name="from"/> <label for="to">to</label> <input type="text" id="to" name="to"/>

I hope you serve, greetings!

    
answered by 03.10.2017 в 19:08
1

Yes it is possible to add the attribute min making use of PHP , your error? the locatime () function returns a array . In addition, the date format must be RFC 3339 .

Then we could use the date () function by passing the respective format:

<div class="form-group">

 <label>Hrs y Fecha de Inicio</label>
 <input type="datetime-local" class="form-control" id="fecha_ini" 
        name="fecha_ini" min="<?php echo  date('Y-m-d\TH:i'); ?>">
</div>
    
answered by 03.10.2017 в 19:12