Search code examples
htmldatevalidationhtml-input

How do I compare two dates in HTML?


This is my code:

<input type="date" name="startDate" id="startDate" />
<input type="date" name="endDate" id="endDate" />

I want startdate to not exceed endDate. is there a way to compare dates without using jQuery? Like in ASP.NET, we can use CompareValidator.


Solution

  • You need to use JavaScript for this.

    function compare()
    {
        var startDt = document.getElementById("startDate").value;
        var endDt = document.getElementById("endDate").value;
    
        if( (new Date(startDt).getTime() < new Date(endDt).getTime()))
        {
            // Your code here
        }
    }
    <input type="date" name="endDate" id="endDate" onblur="compare();"/>

    Do the necessary null validations as well.