Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
527 views
in Technique[技术] by (71.8m points)

html - Restrict future dates in HTML5 date input

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...