patternjavascriptMinor
Date validation with html5 dates
Viewed 0 times
withdatesvalidationdatehtml5
Problem
This code validates the following:
Please review my code. I think I covered all test cases, but I am extremely new to JavaScript, so this code might have bugs. And is it fine to compare dates as strings? I did this because as far as I know HTML5 date is a string.
enddateshould not be less than or equal tostartdate.
startdateshould not be less than or equal to the date today unlessdocument.getElementById("ltype").value == "1".
- The maximum gap between
startdateandenddateis one year, more than that should cause an error alert.
Please review my code. I think I covered all test cases, but I am extremely new to JavaScript, so this code might have bugs. And is it fine to compare dates as strings? I did this because as far as I know HTML5 date is a string.
// creates a date object then converts it to a string with yyyy-mm-dd format
function dateFormat(date, addyear) { // addyear is boolean, true means add another year to the date
var dd = date.getDate();
var mm = date.getMonth()+1;
var yyyy = date.getFullYear();
if (addyear) {
yyyy++;
}
if(dd yeardate) {
alert("Dates out of range");
return false;
}
if (document.getElementById("ltype").value != "1" && startdate <= today) {
alert("Error! date goes backwards!");
return false;
}
return true
}Solution
- Instead of giving your variables names like
dd/mm/yyyy, you should give them names likeday,month,year. Other names liked1ord2. Should have better names.
- You need some space between operators. For example, you have this condition in your code:
if(dd
- You should add some more comments, e.g, describe what the functions/code blocks do, and how the processes behind them work.
- Finally, just a small nitpicky thing. Both of your functions should be in camelCase
. One of them is inunderscore_case`.
Context
StackExchange Code Review Q#94468, answer score: 4
Revisions (0)
No revisions yet.