Skip to content Skip to sidebar Skip to footer

Html5 Date Validation

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 t

Solution 1:

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 timevar t = moment().add("days", 1);
// tomorrow start of dayvar 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!
}

Solution 2:

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 = newDate(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.

functionsetMaxDate() {
    var d1 = document.getElementById('date1');
    var d2 = document.getElementById('date2');
    var t = d1.value.split("-");
    var date = newDate(parseInt(t[0], 10) + 1, parseInt(t[1], 10), t[2]);
    var maxi = date.getFullYear() + "-" + date.getMonth() + "-" + date.getDate();    
    d2.setAttribute("max", maxi);
}

JSFiddle

Solution 3:

Better with javascript. You can I use HTML5 attribute type="date" but keep in mind it's barely supported.

Solution 4:

You can use a Regex pattern like this /([0-9]{2})/([0-9]{2})/([0-9]{4})/, that is, two decimal digits, a slash, two more decimal digits, a slash and four decimal digits, everything grouped separately (group 1 = day, group 2 = month, group 3 = year). You would test for this pattern in a event, (I would suggest onchange, since you mentioned mobile) and also check if the numbers are within a valid range (e.g. day < 32, month < 13, year < currentYear-1).

Post a Comment for "Html5 Date Validation"