I am developing a django app.
I have date input in my form:
<input type="date" name="date_of_birth" max="03.11.2020" max-length="8" pattern="[0-3][0-9].[01][0-9].[0-9]{4}" class="dateinput form-control" required id="id_date_of_birth">
It allows to enter the date with the year having 6 digits, but I wish it was only possible to enter 4. I also tried to write a simple script:
$(function() {
$('#id_date_of_birth').change(function() {
var date = $(this).val();
console.log(date, 'change')
});
});
but it only starts when I change the year.
I would like the numbers to loop on 4 digits instead of 6.
Can someone give me a hint how to limit the year to only 4 digits?
I am developing a django app.
I have date input in my form:
<input type="date" name="date_of_birth" max="03.11.2020" max-length="8" pattern="[0-3][0-9].[01][0-9].[0-9]{4}" class="dateinput form-control" required id="id_date_of_birth">
It allows to enter the date with the year having 6 digits, but I wish it was only possible to enter 4. I also tried to write a simple script:
$(function() {
$('#id_date_of_birth').change(function() {
var date = $(this).val();
console.log(date, 'change')
});
});
but it only starts when I change the year.
I would like the numbers to loop on 4 digits instead of 6.
Can someone give me a hint how to limit the year to only 4 digits?
4 Answers
Reset to default 7I like the suggestion of using the attribute max. Just set the max="9999-12-31" in your input date type field and the year portion will be limited to 4 digits instead of 8. This solved my problem.
Add the attribute max
to fix this. Browsers dont limit the year field to four digits by default.
https://www.w3schools.com/html/tryit.asp?filename=tryhtml5_input_max_min_date
The other answers are correct in the sense that the 'max' attribute will limit the year (at least in Chrome), but the date format is incorrect.
Here's the correct date format
<input type="datetime-local" max="9999-12-31T23:59" name="my-date"/>
I've created a simple jQuery to split the value and check the year if its greater than 4, then use substring then return concatenated values, hope this helps
$('input[type=date]').keyup(function() {
var datevalue = $(this).val();
var dateSplit = datevalue.split("-"); // yyyy-mm-dd
var dateYear = dateSplit[0]; // yyyy
var dateMonth = dateSplit[1]; // mm
var dateDay = dateSplit[2]; // dd
if (dateYear.length > 4) {
dateYear = dateYear.substring(0,4)
$(this).val( dateYear + '-' + dateMonth + '-' + dateDay);
}
});
max
(andmin
) isyyyy-mm-dd
– Andreas Commented Nov 3, 2020 at 10:38datetime-local
, the format isYYYY-MM-DDThh:mm
. (e.g.max="9999-12-31T23:59"
) – Henry Kwon Commented Mar 28, 2022 at 0:06