0

I am beginner in JavaScript, I know the subject exists on StackOverFlow as here below but I don't understand.

Compare two dates with JavaScript

I would like to handle the previous dates for example: We are on 28-05-2020, if the user enters on 27-05-2020 an error message should appear.

For information, I am obliged to use JavaScript to handle the dates.

function validation()
{
    const date_start = document.getElementById('date_start').value;
    const inputDate = new Date(date_start);
    
    const dayFromImputDate = inputDate.getFullYear(); // previous day
    
    const now = new Date();
    const dateNow = now.getFullYear();

    if(dayFromImputDatee < dateNow) {
        document.getElementById('date_startError').innerHTML = " ** Error date ! ";
        return false;
    }

    if(date_start == ""){
        document.getElementById('date_startError').innerHTML = " ** date empty ! ";
        return false;
    }



    console.log("Date is valid");
    return true;
}
<!DOCTYPE html>
<html lang="fr">
<head>
  <meta charset="utf-8">
  <title>Titre de la page</title>
  <link rel="stylesheet" href="style.css">
  <script src="script.js"></script>
</head>
<body>
<form action="#" onsubmit="return validation()" >
<br>
<label>Date start : </label>
<br>
<input type="date" name="date_start" id="date_start">
<br>
<span id="date_startError"></span>
<br>
<input type="submit" value="ok">
</form>
</body>
</html>

Thank you very much for your help and your time.

4 Answers4

0

Because HTML5 already has min and max attributes for the date input type, you don't need to implement a separate validation function to accomplish this. Here is a simpler way:

var date = new Date();
var iso_date = date.toISOString().substring(0, 10);
document.getElementById("date_start").setAttribute('min', iso_date);

Basically, you just get a new Date() object, extract and format it into an ISO 8601 date format, and set it into the min attribute. This also limits the browser selection calendar to future dates only.

Achraf Almouloudi
  • 756
  • 10
  • 27
0

If I understand the problem correctly you are trying to restrict a date form input to the current day or some future date. To check whether a date is valid you could do this:

    let earliestPossibleDate = new Date(
        now.getFullYear(), now.getMonth(), now.getDate()
    );
    let isValidDate = date_start >= earliestPossibleDate
cpt
  • 36
  • 4
0

Three things:

  1. You need to get your Current Date and set time to start of day.
  2. You need to get your Selected Date and set time to start of day
  3. Compare whether Selected Date is Greater or Equal to the Current Date.

Note that when you compare dates, you need to also consider the time. Most calendar tools, include the time as a response to the selected date. You need to be aware of that.

This doesn't include other date validations. This will only solve the current problem at hand. Hope this helps! =)

const isValidDate = (selectedDate) => {
    const currentDate = new Date();

    // reset to start of day
    currentDate.setHours(0);
    currentDate.setMinutes(0);
    currentDate.setSeconds(0);
    currentDate.setMilliseconds(0);

    const newDate = new Date(selectedDate);
    newDate.setHours(0);
    newDate.setMinutes(0);
    newDate.setSeconds(0);
    newDate.setMilliseconds(0);

    return newDate.getTime() >= currentDate.getTime();
}

To use, simply throw the selected date in the function. Should return true if the date is greater or equal to the date today.

isValidDate(selectedDateFromDatePicker);
Algef Almocera
  • 759
  • 1
  • 6
  • 9
0

You can check if input date is less than today's date using < operator

const form = document.querySelector('form');
const error = document.getElementById('date_startError');

function validation(event) {
  event.preventDefault();

  const startDate = form.elements['date_start'].value;

  if (!startDate) {
    error.innerHTML = " ** date empty ! ";
    return;
  }

  const inputDate = new Date(startDate).getDate();
  const today = new Date().getDate();

  if (inputDate < today || !inputDate.valueOf()) {
    error.innerHTML = " ** Error date ! ";
    return;
  }

  error.innerHTML = "date is valid";
}
<form action="#" onsubmit="validation(event)">
  <br>
  <label>Date start : </label>
  <br>
  <input type="date" name="date_start" id="date_start" placeholder="2020-05-28">
  <br>
  <span id="date_startError"></span>
  <br>
  <input type="submit" value="ok">
</form>
Yousaf
  • 27,861
  • 6
  • 44
  • 69
  • Thank you Yousaf, it's ok thank you a lot but it's possible to use my validation function ? Because, I yet am beginner. –  May 28 '20 at 16:04