How to use HTML5 to validate a date range?

Oleg picture Oleg · Oct 8, 2013 · Viewed 9k times · Source

Alternatively, is it possible to validate against another field's value with html5?

A common example would be selecting a date range where "from" date should be less than or equal to "to" date. The following would described the desired relationship between the values, if only you could use element references in syntax:

<input type="date" name="from" max="to">    //todo: populate with ~to.value
<input type="date" name="to" min="from">    //todo: populate with ~from.value

Answer

Oleg picture Oleg · Oct 8, 2013

It's possible to utilize html5 validation mechanism with some javascript to dynamically update min/max attributes:

//in this case a single input restriction is sufficient to validate the form:

$('#from, #to').on('change', function(){
    $('#to').attr('min', $('#from').val());
});

Fiddled. Both min and max could be applied to the respective fields for enhanced UX if browser implementation of a datepicker respects range limitations (by disabling dates outside of the desired range)