Compare two dates in Javascript from an HTML form

1583 views javascript
7

I just started learning php and from time to time I need some JS functions. Today is one of those day. I have an HTML form where I ask for the age of my users and I'd like to check if they put a grater or equal date compared to the today date. This is the HTML code:

<div class="form">
    <form class="login-form" method="POST" action="main.php">
        <input type="date" id="borndate" name="borndate" required="required"/>
    </form>
</div>

And this is my JS script. Note I still need to look at JS and this is just what I thought it could work out:

var borndate = document.getElementById("borndate");
var date = new Date.getFullYear();

function comparedate(){
    if (borndate >= date)
        alert("Looks like you are to young!");
} else {
    return true;
}   

answered question

2 Answers

7

Your code is comparing the element itself with the year. You have to do the comparison with the value of the element. Also you have to convert the value to number.

Change

if (borndate >= date)

To

if (Number(borndate.value) >= date)

posted this
10

I tend to find that libraries make working with dates much easier, and whilst it might be excessive to use one here for something relatively small, you may be interested to see how such an option would work:

var test = dateFns;


function comparedate(){
    var borndate = dateFns.parse(document.getElementById("borndate").value);
    var date = dateFns.parse(new Date());
    
    console.dir(date)
    console.dir(borndate)
    
    if (dateFns.isAfter(borndate, date)) {
        alert("Looks like you are to young!");
    } else {
        return true;
    }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/date-fns/1.29.0/date_fns.min.js"></script>
<div class="form">
    <form class="login-form" method="POST" action="main.php">
        <input type="date" id="borndate" name="borndate" required="required"/>
    </form>
    <button onclick="comparedate()">Compare</button>
</div>

posted this

Have an answer?

JD

Please login first before posting an answer.

Ads

Categories