简体   繁体   English

验证最短日期JavaScript

[英]Validate minimum date JavaScript

I'm trying to validate the minimum date (today) from an object type="date" for a CheckIn until the Checkout and then take the number of days to another variable for further use, all with a button. 我正在尝试从CheckIn的对象类型=“date”验证最小日期(今天),直到Checkout,然后将天数带到另一个变量以供进一步使用,所有这些都使用按钮。 My problem is that I don't really understand how to compare the dates. 我的问题是我真的不明白如何比较日期。

html HTML

<label for="date1"> Checkin </label>
    <input type="date" id="date1">

<label for="date2"> Checkout </label>
    <input type="date" id="date2">

<button type="button" id="btn1" required>Action</button>

js JS

let btn1 = document.getElementById('btn1');
let checkIn = document.getElementById('date1');
btn1.addEventListener('click', minDate);

function minDate(){
    let nowDate = new Date;
    if(checkIn.value < Date){

        alert("invalid date")
    }

}

The function does alert if the date is lower than today but also shows the alert for any date after today. 如果日期低于今天,该功能会发出警报,但也会显示今天之后的任何日期的警报。

Helo Christy. Helo Christy。

In order to validate our date, we must first convert the inputs from the form into javascript Date objects . 为了验证我们的日期,我们必须首先将表单中的输入转换为javascript Date对象 We can do that, by passing the input into the constructor of the class. 我们可以通过将输入传递给类的构造函数来实现。 After that, we can simply compare the values. 之后,我们可以简单地比较这些值。

 const btn1 = document.getElementById("btn1"); const checkIn = document.getElementById("date1"); btn1.addEventListener("click", minDate); function minDate() { const checkInDate = new Date(checkIn.value); const nowDate = new Date(); if (checkInDate > nowDate) { alert("Invalid date provided"); } } 
 <label for="date1"> Checkin </label> <input type="date" id="date1"> <label for="date2"> Checkout </label> <input type="date" id="date2"> <button type="button" id="btn1" required>Action</button> 

Try to do that: 尝试这样做:

function minDate(){

    const nowDate = new Date();
    const valDate = new Date(checkIn.value)

    if(valDate < nowDate){

        alert("invalid date")
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM