Javascript Date Time Validation - Yyyy-mm-dd Hh:mm
I want to create a very simple javascript form validation. I have two input boxes that are populated by a datetime picker. the datetime picker populates the input box with in the f
Solution 1:
GIven the ISO8601 format of the date/time string, you can just compare the values as strings. It's one of the beauties of using an ISO8601 format. You have asked for the delivery time to be after the collection time, which seems backwards to me but anyhow…
<formonsubmit="return checkDates(this)"><table><tr><td><inputtype="text"id="collectdatetime"name="collectdatetime"><td><inputtype="text"id="deliverdatetime"name="deliverdatetime"><td><inputtype="submit"></table></form><script>functioncheckDates(form) {
if (form.collectdatetime.value >= form.deliverdatetime.value) {
alert('Collection time must be after deliver time');
returnfalse;
}
}
</script>
Solution 2:
You could do something like this:
var collectTime = (newDate(document.getElementById("collectdatetime").value)).getTime(),
deliverTime = (newDate(document.getElementById("deliverdatetime").value)).getTime();
if(deliverTime > collectTime) {
//Ok!
}
This creates 2 Date
objects, passing the selected values to the constructor, and then compares the times. The getTime
method returns a number representing the time that has passed since 1 January 1970 00:00:00 in milliseconds.
Here's a working example.
Solution 3:
You can create Date object from this values and compare them:
var collect = newDate($('#collectdatetime').val());
var delivery = newDate($('#deliverdatetime').val());
if (delivery < collect) {
alert('Delivery date before collect!');
}
Post a Comment for "Javascript Date Time Validation - Yyyy-mm-dd Hh:mm"