date validation in javascript – How to check a date is valid or not using JavaScript?

date validation in javascript – Validate Date Using Regular Expressions, the moment.js Library and Date.parse() Method in JavaScript Example with demo.

How to check a date is valid or not using JavaScript?

A JavaScript function is used to check a valid date format against a regular expression.

Date Validation as Text Format in JavaScript

Validation Function

function validatedate(dateString){      
    let dateformat = /^(0?[1-9]|1[0-2])[\/](0?[1-9]|[1-2][0-9]|3[01])[\/]\d{4}$/;      
              
    if(dateString.match(dateformat)){      
        let operator = dateString.split('/');      
            
        let secDateInfo = [];      
        if (operator.length>1){      
            secDateInfo = dateString.split('/');      
        }      
        let curr_mon= parseInt(secDateInfo[0]);      
        let day = parseInt(secDateInfo[1]);      
        let year = parseInt(secDateInfo[2]);      
                    
        let totalNoOfDays = [31,28,31,30,31,30,31,31,30,31,30,31];      
        if (curr_mon==1 || curr_mon>2){      
            if (day>totalNoOfDays[curr_mon-1]){            
                return false;      
            }      
        }else if (curr_mon==2){      
            let applpYear = false;      
            if ( (!(year % 4) && year % 100) || !(year % 400)) {      
                applpYear = true;      
            }      
            if ((applpYear == false) && (day>=29)){      
                return false;      
            }else      
            if ((applpYear==true) && (day>29)){      
                console.log('Sorry, Invalid date format!');      
                return false;      
            }      
        }      
    }else{      
        console.log("Invalid date format!");      
        return false;      
    }      
    return true;      
}   

Example

var a = validatedate("06/16/2021");    
console.log(a);   

Sample Regex for Date Format

Date Format Regex
MM/DD/YYYY  
M/DD/YYYY /^(0?[1-9]|1[0-2])[\/](0?[1-9]|[1-2][0-9]|3[01])
MM/D/YYYY [\/]\d{4}$/
M/D/YYYY  
DD/MM/YYYY  
D/MM/YYYY  /^(0?[1-9]|[1-2][0-9]|3[01])[\/](0?[1-9]|1[0-2])
DD/M/YYYY  [\/]\d{4}$/
D/M/YYYY  

Don’t Miss : Timestamp To Date Javascript

Validate Date With With Date.parse() Method in JavaScript

Date Validation as Text Format in JavaScript – The Data.parse() is a function that is already available in core JavaScript.

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Validate Date With With Date.parse() Method in JavaScript - www.pakainfo.com</title>
  </head>
  <body>
    <h2 id="pakainfo_new_dsiplay_status"></h2>

    <script>
        let isValidDate = Date.parse('03/17/21');

        if (isNaN(isValidDate)) {
          document.getElementById('pakainfo_new_dsiplay_status').innerHTML = "It is not a valid date format.";
        }
        else{
          document.getElementById('pakainfo_new_dsiplay_status').innerHTML = "It is a valid date format.";
        }

    </script>
  </body>
</html>

Validate Date Using Regular Expressions in JavaScript

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Document</title>
  </head>
  <body>
    <h2 id="pakainfo_new_dsiplay_status"></h2>
    <script>
      
      var date_regex = /^(0[1-9]|1[0-2])\/(0[1-9]|1\d|2\d|3[01])\/(0[1-9]|1[1-9]|2[1-9])$/;
        var testDate = "03/17/21"
        if (date_regex.test(testDate)) {
            document.getElementById("pakainfo_new_dsiplay_status").innerHTML = "Date follows dd/mm/yy format";
        }
        else{
          document.getElementById("pakainfo_new_dsiplay_status").innerHTML = "Invalid date format";
        }

    </script>
  </body>
</html>

Validate Date With the moment.js Library in JavaScript

First of all open your cmd terminal and run this bellow commands.

Also Read This 👉   500 internal server error ajax


npm install -g moment --save 

Example

import * as moment from 'moment';

let result = moment("05/22/21", 'MM/DD/YY',true).isValid();
console.log(result)

Date of Birth (Age) Validation in JavaScript

HTML Markup

<input type="text" id="txtDate" onblur = "CheckBirthDate()" />
<span class="error" id="displayErr"></span>
<br />
<br />
<input type="button" id="btnValidate" value="Validate" onclick="return CheckBirthDate()" />

Date of Birth (Age) Validation in JavaScript

<script type="text/javascript">
    function CheckBirthDate() {
        var displayErr = document.getElementById("displayErr");
 
        var dateString = document.getElementById("txtDate").value;
        var regex = /(((0|1)[0-9]|2[0-9]|3[0-1])\/(0[1-9]|1[0-2])\/((19|20)\d\d))$/;
 
        if (regex.test(dateString)) {
            var infoChecks = dateString.split("/");
            var bDate = new Date(infoChecks[1] + "/" + infoChecks[0] + "/" + infoChecks[2]);
            var activeDt = new Date();
            displayErr.innerHTML = "Hello Dear , Eligibility 18 years ONLY."
            if (activeDt.getFullYear() - bDate.getFullYear() < 18) {
                return false;
            }
 
            if (activeDt.getFullYear() - bDate.getFullYear() == 18) {
 
                if (activeDt.getMonth() < bDate.getMonth()) {
                    return false;
                }
                if (activeDt.getMonth() == bDate.getMonth()) {
                    if (activeDt.getDate() < bDate.getDate()) {
                        return false;
                    }
                }
            }
            displayErr.innerHTML = "";
            return true;
        } else {
            displayError.innerHTML = "Enter date in dd/MM/yyyy format ONLY."
            return false;
        }
    }
</script>

Don’t Miss : How To Get Current Date & Time In JavaScript?

I hope you get an idea about date validation in javascript.
I would like to have feedback on my infinityknow.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.