I'm looking to implement validation for a mobile site, where I have two input fields and I would like the first to validate the value is no later than todays date, and the second to validate it is no later than a one year in advance of the first value.
E.g
Is this possible?
I like moment.js. It makes it easier to deal with dates and times.
First, let's make sure a day "is before tomorrow". This will depend a bit upon what the definition of tomorrow is.
var m = moment("26/11/2013", "MM/DD/YYYY");
// tomorrow this time
var t = moment().add("days", 1);
// tomorrow start of day
var tomorrow = moment([t.year(), t.month(), t.date()]);
if (m.lessThan(tomorrow)) {
   // today!!! (or before)
}
Similarly, the same approach can be used for a year from now. It's likely fine enough to not care about the time component in this case, and I've slogged on another day - but if it matters (e.g. looking for the start of the day), see the previous example.
var m = moment("26/11/2013", "MM/DD/YYYY");
var aYearFromNow = moment().add("years", 1).add("days", 1);
if (m.lessThan(aYearFromNow)) {
   // still less than a year!
}
                        1) cache the elements.
var d1 = document.getElementById('date1');
var d2 = document.getElementById('date2');
2) The value of d1 and d2 are string data type.  So split them and parse it to date format as below
var t = d1.value.split("-");
var date = new Date(parseInt(t[0], 10) + 1, parseInt(t[1], 10), t[2]);
Here the year is incremented by 1, based on the value in d1.
4) Again parse it back to string format (YYYY-MM-DD)
var maxi = date.getFullYear() + "-" + date.getMonth() + "-" + date.getDate();    
5) Set this as value for max attribute for d2
d2.setAttribute("max", maxi);
Finally add the below method to onblur event of d1.  
function setMaxDate() {
    var d1 = document.getElementById('date1');
    var d2 = document.getElementById('date2');
    var t = d1.value.split("-");
    var date = new Date(parseInt(t[0], 10) + 1, parseInt(t[1], 10), t[2]);
    var maxi = date.getFullYear() + "-" + date.getMonth() + "-" + date.getDate();    
    d2.setAttribute("max", maxi);
}
JSFiddle
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With