Search code examples
javascriptjqueryvalidation

Validate date so that the date cannot be in future or in past


I have this form that has a date input. What is the best way in Javascript that I can ensure the value selected is neither a future date or a past date. I have implemented jQuery date picker to select date see code below

<html>
  <!--maina-->
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
  <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<link href="main.css" rel="stylesheet" type="text/css"/>

<script>
$(function() {
    var date = $('#datepicker').datepicker({ dateFormat: 'yy-mm-dd' }).val();
});

function ValidateForm(){
	var date_of_circulation = document.forms["myForm"]["date_of_circulation"].value;
		if (date_of_circulation == null || date_of_circulation ==""){
			alert ("You have to select the date the manuscript was circulated");
			return false;
		}
	}
</script>

<form enctype="multipart/form-data" name = "myForm" action = "" onsubmit="return ValidateForm()" method = "post">
Date of circulation:<input name="date_of_circulation" input type="text" id="datepicker"></p>
<input name = "add_manuscript" type="submit" value = "submit">
</form>
</html>


Solution

  • You can do it like this

    var yourDate = new Date("12/5/2015"); //input value
    
    var todayDate = new Date(); //Gets the today's date value
    

    You have to use function setHours

    if(yourDate.setHours(0,0,0,0) == todayDate.setHours(0,0,0,0));
    {
        //Do your stuff
    }
    

    NOTE: You can also do it using the jquery's datepicker

    var currentDate = new Date();
    $("#datepicker").datepicker("setDate", currentDate);
    

    so that you can be sure that today's date is already selected.

    EDIT: You can also look at datejs

    datejs API Documentation