2

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.

TylerH
  • 20,799
  • 66
  • 75
  • 101
anthony levano
  • 68
  • 1
  • 1
  • 8
  • @AlexK. @MarkB You can use the `min` and `max` HTML attributes, but they're not bulletproof. Possible duplicate of [input type date min and max values validate against yyyy-mm-dd instead of dd-mm-yyyy](http://stackoverflow.com/questions/17443034/input-type-date-min-and-max-values-validate-against-yyyy-mm-dd-instead-of-dd-mm) – Blazemonger Jan 12 '16 at 15:29

1 Answers1

4

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.

TylerH
  • 20,799
  • 66
  • 75
  • 101
Let'sRefactor
  • 3,303
  • 4
  • 27
  • 43
  • The correct API is to get the `valueAsDate` property. What this answer is doing is passing the string from the `value` property to the `Date` constructor, which is wrong. _“Note: Parsing of date strings with the `Date` constructor (and `Date.parse`, which works the same way) is **strongly discouraged** due to browser differences and inconsistencies.”_ — From the [documentation](//developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/Date#parameters). – Sebastian Simon Dec 14 '21 at 19:29