How to validate a date pattern in JavaScript?

JavascriptWeb DevelopmentFront End Technology

To validate a date pattern in JavaScript, try to run the following code. Here, we will check for correct as well as incorrect dates to validate

Example

Live Demo

<!DOCTYPE html>
<html>
   <body>
   
      <script>
         function validDate(date) {
            var split = date.split('/');
            var date = new Date(split[2] + '/' + split[0] + '/' + split[1]);
            return (date &amp;&amp; (date.getMonth() + 1) == split[0] &amp;&amp; date.getDate() == Number(split[1]) &amp;&amp; date.getFullYear() == Number(split[2]));
         }
         document.write("Valid date: 11/11/2017 = "+validDate('11/11/2017'));
         document.write("<br>Valid date: 18/18/2017 = "+validDate('18/18/2017'));
         document.write("<br>Valid date: 05/09/2017 = "+validDate('05/09/2017'));
      </script>
      
   </body>
</html>

Output

Valid date: 11/11/2017 = true
Valid date: 18/18/2017 = false
Valid date: 05/09/2017 = true
raja
Updated on 30-Jul-2019 22:30:21

Advertisements