How to validate number of days in a given month with JavaScript?

Sometimes, we want to validate number of days in a given month with JavaScript.

In this article, we’ll look at how to validate number of days in a given month with JavaScript.

How to validate number of days in a given month with JavaScript?

To validate number of days in a given month with JavaScript, we can write our own function to check the number of days of a given month.

For instance, we write:

const daysInMonth = (m, y) => {
  switch (m) {
    case 1:
      return (y % 4 == 0 && y % 100) || y % 400 == 0 ? 29 : 28;
    case 8:
    case 3:
    case 5:
    case 10:
      return 30;
    default:
      return 31
  }
}

const isValid = (d, m, y) => {
  return m >= 0 && m < 12 && d > 0 && d <= daysInMonth(m, y);
}

console.log(isValid(20, 1, 2022))
console.log(isValid(30, 1, 2022))

to define the daysInMonth function that takes month m and year y as parameters.

m is between 0 and 11 where 0 is January and 11 is December.

In the function, we check if February is in a leap year.

If it is, 23 return 29 and 28 otherwise.

For the other months, we check whether the month has 30 or 31 days.

Then we define the isValid function that takes day d, month m and year y.

In the function, we check if m is between 0 and 11, and d is in the valid range for the month.

Therefore, the first log is true and the 2nd is false.

Conclusion

To validate number of days in a given month with JavaScript, we can write our own function to check the number of days of a given month.