user3350885 user3350885 - 1 month ago 10
jQuery Question

jQuery validation for from and to dates without any jQuery plugins

I have tried three set of code using Stack Overflow. I know that some parsing/date manipulation needed for jQuery validation.

The start date and end date validation needs to be implemented in my project. If I alert I'm able to get both the start and end date in my alert box.


  1. The start and end date will be in the format DD-MM-YYYY

  2. I don't want to use any jQuery validator plugin (.js files) other than my jquery.js file.

  3. Just I need to check one condition that the end date is greater than start date.



In other words, a two line code to check the start and end date.

<script type="text/javascript" src="jquery-1.11.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$( "#my_form" ).submit(function( event ) {
//first set of code
var date_ini = new Date($('#from_date').val()).getTime();
var date_end = new Date($('#to_date').val()).getTime();
if (date_ini < date_end) {
alert('Invalid');
}

//second set of code
var from = Date.parse($("#from_date").val());
var to = Date.parse($("#to_date").val());
if(from < to){
alert("Invalid Date Range");
}
else{
alert("Valid date Range");
}

//third set of code
var startDate = new Date($('#from_date').val());
var endDate = new Date($('#to_date').val());
if (startDate < endDate){
alert('Invalid');
}

});
});

</script>


<form id="my_form" class="my_form">
<table>
<tr><td>From Date</td><td><input type="text" name="from_date" id="from_date" /></td></tr>
<tr><td>To Date</td><td><input type="text" name="to_date" id="to_date" /></td></tr>
<tr><td><input type="submit" value="submit" /></td></tr>
</table>
</form>

Answer

Try this code:

$(document).ready(function()
    {
    $( "#my_form" ).submit(function( event ) {
    //first set of code 
    var date_ini = getDate($('#from_date').val()) ;
    var date_end = getDate($('#to_date').val());

    if (date_ini < date_end) {
    alert('valid');
        //put code here to call server
    }
        else
        {
            alert('Invalid');
            return false;
        }



    });
    });

function getDate(input)
{
 from = input.split("-");
return new Date(from[2], from[1] - 1, from[0]);   
}

Click here to see the working example: http://jsfiddle.net/SS597/1/