I have a date control which has a dropdown for each date, month and year.
The issue is, I can select 31st Nov. 2015 as well, and when I create date object, I get 1st Dec. 2015.
Example
var _date = 31; // value fetched from dropdown
var _month = 10;
var _year = 2015;
var date = new Date(_year, _month, _date);
document.write(date)
I want to validate this condition, and my current approach is to match date.getDate()
with _date
and show an error message if they are different.
Is there a better way to implement this?
Code
var _monthList = [
{id:"1",name:"January"} ,
{id:"2",name:"February"} ,
{id:"3",name:"March"} ,
{id:"4",name:"April"} ,
{id:"5",name:"May"} ,
{id:"6",name:"June"},
{id:"7",name:"July"} ,
{id:"8",name:"August"} ,
{id:"9",name:"September"} ,
{id:"10",name:"October"} ,
{id:"11",name:"November"} ,
{id:"12",name:"December"}];
function createYears(){
var _year = [];
for (var i = 2000; i<=new Date().getFullYear(); i++){
_year.push({id:i, name:i});
}
$("#cbYear").html(createOptions(_year));
}
function createMonths(){
$("#cbMonth").html(createOptions(_monthList));
}
function createDates(){
var _dates = [];
for (var i=1; i<=31; i++){
_dates.push({id:i, name:i});
}
$("#cbDate").html(createOptions(_dates));
}
function createOptions(dataset){
var optionStr = "<option></option>";
$.each(dataset, function(key, value){
var id = value.id? value.id:key;
var text = value.name;
var val = value.value?value.value:value.id;
optionStr += "<option id="+ id + " name='"+ text+ "' value='"+ val + "'>"+ text + "</option>"
});
return optionStr;
}
function registerEvents(){
$("select").on("change", function(e){
validateDate();
});
}
function validateDate(){
var _date = $("#cbDate option:selected").val();
var _month = $("#cbMonth option:selected").val();
var _year = $("#cbYear option:selected").val();
if(_year && _month && _date){
var dateObj = new Date(_year, _month-1, _date);
if(_date != dateObj.getDate()){
$("#lblError").text("Please Select a valid date");
}
else{
$("#lblError").text("");
}
}
}
(function(){
createYears();
createMonths();
createDates();
registerEvents();
})()
select{
background:#fff;
color:blue;
width:100px;
padding:5px;
border-radius:4px;
border: 1px solid gray;
}
.error{
color:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select id="cbYear"></select>
<select id="cbMonth"></select>
<select id="cbDate"></select>
<br />
<span id="lblError" class="error"></span>
Use Case
Select: Invalid Date (e.g. 31st Nov.)
I have also created a JSFiddle for the same.