Javascript validate date string | regular expression, format, parse methods

Using Date.parse() method you can validate the date string in Javascript. the parse() method parses a string representation of a date and returns the number of milliseconds. If the given string doesn’t represent a valid date, NaN is returned.

Examples of JavaScript validate date string

Simple date validation in JavaScript using parse method:-

<!DOCTYPE html> 
<html> 
    <body> 
        <script> 
       	var sd = "Dec 01, 2020"

        alert(Date.parse(sd));

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

Output:

Simple date validation in javascript

Another Example and Improved function that uses only Date.parse():

<!DOCTYPE html> 
<html> 
    <body> 
        <script> 
       	var sd = "Dec 01, 2020"

       	function isDate(s) {
    		if(isNaN(s) && !isNaN(Date.parse(s)))
        		return true;
    		else return false;
		}

        alert(isDate(sd));

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

Output:

Javascript validate date string

Date validation in javascript using regular expression

Let’s see the example of how to validate date format in JavaScript using regex.

Example of JavaScript validate date format dd-mmm-yyyy

<!DOCTYPE html> 
<html> 
    <body> 
    	<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
     
	<input type="text" id="txtEnteredStartDate" value="19-Dec-2020" />
	<input type="button" class="check" value="check" /><br>
	<span class="result"></span>

        <script> 
       	function ValidateDate() {
  		var dtValue = $('#txtEnteredStartDate').val();
  		var dtRegex = new RegExp("^([0]?[1-9]|[1-2]\\d|3[0-1])-(JAN|FEB|MAR|APR|MAY|JUN|JULY|AUG|SEP|OCT|NOV|DEC)-[1-2]\\d{3}$", 'i');
  		return dtRegex.test(dtValue);
		}

	$('.check').click(function() {
  		if (ValidateDate() == false) {
    	$('.result').html("Wrong Date Format");
  	} else {
    	$('.result').html("Right Date Format");
  	}
	});


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

Output:

javascript validate date format dd-mmm-yyyy using regular expression

Javascript validate date format dd-mm-yyyy

<!DOCTYPE html> 
<html> 
    <body> 
    	<script type="text/javascript">
    		var input = '01/01/2020';

			var pattern =/^([0-9]{2})\/([0-9]{2})\/([0-9]{4})$/;

			alert(pattern.test(input));
    	</script>
    </body> 
</html>

Current date validation in javascript

Date validation is needed when you want to restrict the user to provide a future date.

<!DOCTYPE html> 
<html> 
    <body> 
    	<script>
    		var GivenDate = '2020-09-20';
			var CurrentDate = new Date();
			GivenDate = new Date(GivenDate);

		if(GivenDate > CurrentDate){
    		alert('Given date is greater than the current date.');}
		else{
    	alert('Given date is not greater than the current date.');
		}
    	</script>
    </body> 
</html>

Output:

Current date validation in javascript

Q: How to date range validation in JavaScript?

Answer: Checks to ensure that the values entered are dates and /are of a valid range. By this, the dates must be no more than the built-in number of days apart.

the multiplier for 86400000 should be whatever the range of days you are looking for is. So if you are looking for dates that are at least one week apart then it should be seven.

Complete code for date range check:-

<!DOCTYPE html> 
<html> 
    <body> 
    	<script>
    		function checkDateRange(start, end) {
   // Parse the entries
   var startDate = Date.parse(start);
   var endDate = Date.parse(end);
   // Make sure they are valid
    if (isNaN(startDate)) {
      alert("The start date provided is not valid, please enter a valid date.");
      return false;
   }
   if (isNaN(endDate)) {
       alert("The end date provided is not valid, please enter a valid date.");
       return false;
   }
   // Check the date range, 86400000 is the number of milliseconds in one day
   var difference = (endDate - startDate) / (86400000 * 7);
   if (difference < 0) {
       alert("The start date must come before the end date.");
       return false;
   }
   if (difference <= 1) {
       alert("The range must be at least seven days apart.");
       return false;
    }
   return true;
	}

	//test
	alert(checkDateRange('10/10/2008','10/19/2008'))
    	</script>


    </body> 
</html> 

Output:

date range validation in javascript

Do comment if you have any questions and suggestions on this topic.

Note: The All JS Examples codes are tested on the Safari browser (Version 12.0.2) and Chrome.
OS: macOS 10.14 Mojave
Code: HTML 5 Version


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.