![]() |
These damn bugs are everywhere... |
Back in October, I encountered this one. This was on a certain web form. Customers would key in certain details on the form to place an order, among which was a date input which they used to state the expected date of delivery. However, they should only be allowed to key in a date that was three days from the current date, in order to give the Operations and Logistics Team time to get things ready.
This was simple enough. In the form, the HTML5 input occupied these couple lines.
<b>Delivery Date: </b>
<input type="date" id="dtDelivery" name="dtDelivery" />
<input type="date" id="dtDelivery" name="dtDelivery" />
The client-side JavaScript code calculated the correct date and set the min attribute to that value. The min attribute would only accept dates in the format YYYY-mm-dd, which was why I had to separate out month and date values before recombining them.
function adjustMinDate(id)
{
var dt = document.getElementById(id);
var today = new Date(2024,11,30);
today.setDate(today.getDate() + 3);
var dayStr = (today.getDate() < 10 ? "0" + today.getDate() : today.getDate());
var monthStr = today.getMonth() + 1;
var dtStr = today.getFullYear() + "-" + monthStr + "-" + dayStr;
dt.min = dtStr;
}
{
var dt = document.getElementById(id);
var today = new Date(2024,11,30);
today.setDate(today.getDate() + 3);
var dayStr = (today.getDate() < 10 ? "0" + today.getDate() : today.getDate());
var monthStr = today.getMonth() + 1;
var dtStr = today.getFullYear() + "-" + monthStr + "-" + dayStr;
dt.min = dtStr;
}
So, on 5th October, the user was only able to select dates from 8th October onward!
Looked simple enough. It worked, didn't it? Until it didn't.
What Went Wrong
However, at the end of the year, I was alerted by a concerned Operations and Logistics Team that customers had started sending them impossible delivery dates, which meant that the date input was no longer restricting users! When I checked, I was able to select dates even before the current date, which was 30th December.Why It Went Wrong
I inspected the code at run-time, and this is what I found. The month value was missing a preceding zero.Now this would not have been a problem in December - because 12 is a two-digit number and does not require a preceding zero. But once January arrived, it needed to be "2025-01-02" instead of "2025-1-02". Otherwise, the format would be invalid and the min attribute would fail quietly.
How I Fixed It
It was just a matter of adding a preceding zero to any month value that was less than 10.var monthStr = (today.getMonth() + 1 < 10 ? "0" + (today.getMonth() + 1) : today.getMonth() + 1);
And now, in January, it worked! I could not select any date before the 4th of January.
Moral of the Story
Some things are time-sensitive. Including, well, time. Therefore it's possible something that performed perfectly a few days ago could fail later on.T00dles for n0w,
T___T
T___T
No comments:
Post a Comment