Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Restrict future dates in HTML5 date input

Tags:

html

I want to restrict a user to only being able to add future dates in a HTML date input.

Instead of jQuery UI date picker I want to add HTML5 calender. Can anyone tell me how can I restrict the input to future dates?

like image 877
Erandi Avatar asked May 15 '14 07:05

Erandi


People also ask

How do you restrict date input in HTML?

jQuery codegetFullYear(); if(month < 10) month = '0' + month. toString(); if(day < 10) day = '0' + day. toString(); var maxDate = year + '-' + month + '-' + day; $('#txtDate').

How do I change the input date format in html5?

To set and get the input type date in dd-mm-yyyy format we will use <input> type attribute. The <input> type attribute is used to define a date picker or control field. In this attribute, you can set the range from which day-month-year to which day-month-year date can be selected from.

How do I set the calendar to not allow dates before today's date in HTML?

toISOString(). split('T')[0]; document. getElementsByName("setTodaysDate")[0]. setAttribute('min', today);


3 Answers

You can use min and max attributes of HTML5 input date

HTML5 code

<input type="date" name="bday" min="2014-05-11" max="2014-05-20">

EDIT

You need to use jQuery to achieve it

jQuery code

$(function(){
    var dtToday = new Date();

    var month = dtToday.getMonth() + 1;
    var day = dtToday.getDate();
    var year = dtToday.getFullYear();

    if(month < 10)
        month = '0' + month.toString();
    if(day < 10)
        day = '0' + day.toString();

    var maxDate = year + '-' + month + '-' + day;    
    $('#txtDate').attr('max', maxDate);
});

Explanation max attribute of HTML5 input date takes month and day in double digit format.

Ex: 5 (Month) is not valid whereas 05 (Month) is valid Ex: 1 (Day) is not valid whereas 01 (Day) is valid

So I have added below code

if(month < 10)
   month = '0' + month.toString();
if(day < 10)
   day = '0' + day.toString();

Check my updated fiddle

Refer fiddle demo

like image 127
Chirag Vidani Avatar answered Oct 17 '22 10:10

Chirag Vidani


To build on @Chirag Vidani's answer, the date can be generated with fewer lines like this:

var now = new Date(),
    // minimum date the user can choose, in this case now and in the future
    minDate = now.toISOString().substring(0,10);

$('#my-date-input').prop('min', minDate);
like image 21
Juank Avatar answered Oct 17 '22 10:10

Juank


Here is a PHP solution that gets today's date and sets it as the maximum.

<input type="date" name="bday" max="<?php echo date("Y-m-d"); ?>">

This will put it in the correct double-digit format for the day and month. https://www.php.net/manual/en/function.date.php

like image 9
Painguin Avatar answered Oct 17 '22 12:10

Painguin