3
\$\begingroup\$

This code validates the following:

  • enddate should not be less than or equal to startdate.
  • startdate should not be less than or equal to the date today unless document.getElementById("ltype").value == "1".
  • The maximum gap between startdate and enddate is 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<10) {
 dd='0'+dd;
 } 
 if(mm<10) {
 mm='0'+mm;
 } 
 return yyyy+'-'+mm+'-'+dd;
}
function date_compare() {
 var today = dateFormat(new Date(),false);
 // from and to are html5 date fields
 var d1=document.getElementById("from").value;
 var d2=document.getElementById("to").value;
 var startdate = dateFormat(new Date(d1),false);
 var enddate = dateFormat(new Date(d2),false);
 var yeardate = dateFormat(new Date(d1),true);
 if (enddate <= startdate || enddate > 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
} 
Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Jun 23, 2015 at 17:36
\$\endgroup\$

1 Answer 1

4
\$\begingroup\$
  1. Instead of giving your variables names like dd/mm/yyyy, you should give them names like day, month, year. Other names like d1 or d2. Should have better names.
  2. You need some space between operators. For example, you have this condition in your code: if(dd<10). Stuff like this can be expanded to if(dd < 10). Variable definitions should also not look like this: var x=...;, but rather, var x = ...;.
  3. You should add some more comments, e.g, describe what the functions/code blocks do, and how the processes behind them work.
  4. Finally, just a small nitpicky thing. Both of your functions should be in camelCase. One of them is in underscore_case.
answered Jun 23, 2015 at 18:11
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.