How to validate a date pattern in JavaScript?


In this tutorial, we will learn how to validate a date pattern in JavaScript.

The Date object in JavaScript represents a single point in time in a platform-independent way. It carries a number representing time in milliseconds since January 1, 1970, at 00:00:00. (UTC). The Date object can format differently, so it is essential to validate a date pattern before using it.

In this tutorial, we will discuss two ways to validate a date pattern in JavaScript −

  • Using the getTime() method
  • Using the Date constructor and split() method

Validate a Date Pattern using the getTime() Method

In JavaScript, the getTime() method returns the time in milliseconds since January 1, 1970, at 00:00:00. (UTC). Firstly, we create a JavaScript date object by passing the date pattern in the Date constructor, and then we call the getTime() method on it. If the provided pattern is invalid, this method returns NaN (not a number).

Syntax

const isValid = new Date('14/14/2022').getTime()
console.log(isValid) //NaN
if (isNaN(isValid)) {
   console.log('Date pattern is invalid')
} else {
   console.log('Date pattern is valid')
}

In the above syntax, we use a date pattern ‘14/14/2022’ to create a Date object and use the getTime() method. After that, the return value of the getTime() method is checked to determine whether it is NaN or not using the isNaN() method. If the value is NaN, then the date pattern is invalid.

Example

In the below example, we validate multiple date patterns in JavaScript. The button “Validate” is associated with a click event that triggers the function “validatePattern()” whenever the user clicks on the button. This function uses the Date constructor and the getTime() method to validate the date patterns.

<html> <head> <style> .element { padding: 15px; margin-top: 5px; background-color: rgb(169, 231, 224); border: 1px solid black; } </style> </head> <body> <h2>Validating the date pattern with JavaScript using the<i>getTime() method</i></h2> <button onclick = "validatePattern()">Validate</button> <div id = "element1" class = "element">1/1/2022</div> <div id = "element2" class = "element">14/14/2022</div> <div id = "element3" class = "element">10-10-2000</div> <div id = "element4" class = "element">32-32-2000</div> <div id = "element5" class = "element">January 1 2022</div> <div id = "element6" class = "element">January 35 2022</div> <script> // All elements const element1 = document.getElementById('element1') const element2 = document.getElementById('element2') const element3 = document.getElementById('element3') const element4 = document.getElementById('element4') const element5 = document.getElementById('element5') const element6 = document.getElementById('element6') // All date patterns const date1 = '1/1/2022' const date2 = '14/14/2022' const date3 = '10-10-2000' const date4 = '32-32-2000' const date5 = 'January 1 2022' const date6 = 'January 35 2022' // "Validate" button click event handler function function validatePattern() { element1.innerHTML = date1 + ' = ' + validate(date1) element2.innerHTML = date2 + ' = ' + validate(date2) element3.innerHTML = date3 + ' = ' + validate(date3) element4.innerHTML = date4 + ' = ' + validate(date4) element5.innerHTML = date5 + ' = ' + validate(date5) element6.innerHTML = date6 + ' = ' + validate(date6) } function validate(pattern) { const isValid = new Date(pattern).getTime() if (isNaN(isValid)) { return 'invalid' } else { return 'valid' } } </script> </body> </html>

Validate a Date Pattern using the Date Constructor and split() Method

In this approach, we take the date pattern and split it into an array using the split() method; then, we create a JavaScript date object with the array elements. After that, we check the date object’s month, date, and year with the date pattern. If the Date object is invalid or the day, month, or year does not match the date pattern, then the date pattern should be considered invalid. This approach can only be used for the ‘MM/DD/YYYY’ type of date pattern.

Syntax

function validate(date) {
   var split = date.split('/')
   var date = new Date(split[2] + '/' + split[0] + '/' + split[1])
   return (
      date &&
      date.getMonth() + 1 == split[0] &&
      date.getDate() == Number(split[1]) &&
      date.getFullYear() == Number(split[2])
   )
}

In the above syntax, the validate function uses the Date constructor and split method to validate the date pattern.

Example

In the below example, we validate a date pattern with JavaScript using the Date constructor and split method. First, the users can put their date pattern in the input field. Then, a button “Validate” is used that executes the “validate()” function on the click event. This function validates the user input date pattern and shows the output.

<html> <body> <h2>Validating the date pattern with JavaScript using the<i>the Date constructor</i> and <i>the split method</i></h2> <h4>Enter the date pattern:</h4> <input type="text" id="date-pattern" name="date-pattern" value = "11/07/2022"/> <button onclick = "validatePattern()"> Validate </button> <div id="root" style="padding: 15px; margin-top: 5px; background-color: rgb(169, 231, 224); border: 1px solid black;"> </div> <script> // "Validate" button click event handler function function validatePattern() { // user input value const date_pattern = document.getElementById('date-pattern').value const root = document.getElementById('root') root.innerHTML = date_pattern + ' = ' + validate(date_pattern) } function validate(date) { var split=date.split('/') var date = new Date(split[2] + '/' + split[0] + '/' + split[1]) return ( date && date.getMonth() + 1 == split[0] && date.getDate() == Number(split[1]) && date.getFullYear() == Number(split[2]) ) } </script> </body> </html>

In this tutorial, we have learned how to validate date patterns with JavaScript. We have discussed two approaches: the getTime() method and the Date constructor and split() method. Users can follow any of these as per their requirements.

Updated on: 31-Oct-2022

341 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements