How to Validate String Date Format in JavaScript ?
Last Updated :
28 May, 2024
Validating string date format in JavaScript involves verifying if a given string conforms to a specific date format, such as YYYY-MM-DD or MM/DD/YYYY. This ensures the string represents a valid date before further processing or manipulation.
There are many ways by which we can validate whether the Date format is correct or not, Let's discuss each of them one by one.
We will explore all the above methods along with their basic implementation with the help of examples.
Approach 1: Using the Date.parse() Inbuild Function
In this approach, we are using Date.parse() which takes a string as an argument to calculate the milliseconds since "1-jan-1970" and returns the result in milliseconds. NaN will check for the number validation if it returns false means it is not a valid date else it is a valid date.
Syntax:
Date.parse( datestring );
Example: It describes the validation of date format using the Date.parse() inbuild function.
JavaScript
// Creating variables
let Date1 = "2023-08-25";
let Date2 = "Invalid date string format";
// Function for validation of date format
function isValidDate(stringDate) {
return !isNaN(Date.parse(stringDate));
}
// Displaying the result
console.log(isValidDate(Date1));
console.log(isValidDate(Date2));
Approach 2: Using Regular Expression
For date format validation, we are using regular expressions. This entails creating a pattern to match particular text formats, which can be customized according to the required date format.
Type of formats:
- "YYYY-MM-DD"
- "DD-MM-YYYY"
- "DD/MM/YYYY"
Syntax:
// Format 1: "YYYY-MM-DD"
const regex = /^\d{4}-\d{2}-\d{2}$/;
// Format2 : "DD-MM-YYYY"
const regex = /^(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])-(\d{4})$/;
// Format3 : "DD/MM/YYYY"
const regex = /^(0[1-9]|1[0-2])\/(0[1-9]|1[0-2])\/\d{4}$/;
Example: It describes the string date validation using regular expressions in different ways.
JavaScript
let Date1 = "06-24-2013";
let Date2 = "2013-18-09";
// Format 1: "YYYY-MM-DD" (Y-year, M- month, D - date)
function isValidDate(stringDate) {
const regex = /^\d{4}-\d{2}-\d{2}$/;
return regex.test(stringDate);
}
console.log(isValidDate(Date1)); // Output: false
console.log(isValidDate(Date2)); // Output: true
// Format2 : "DD-MM-YYYY" (Y-year , M- month , D - date)
let Date3 = "2013-18-09";
let Date4 = "06-24-2013";
function isValidDate1(stringDate) {
const regex = /^(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])-(\d{4})$/;
return regex.test(stringDate);
}
console.log(isValidDate1(Date3)); // Output: false
console.log(isValidDate1(Date4)); // Output: true
// Format3 : "DD/MM/YYYY" (Y-year , M- month , D - date)
let Date5 = "2013-18-09";
let Date6 = "06-24-2013";
let Date7 = "06/12/2013";
let Date8 = "06/4/2013";
function isValidDate2(stringDate) {
const regex = /^(0[1-9]|1[0-2])\/(0[1-9]|1[0-2])\/\d{4}$/;
return regex.test(stringDate);
}
console.log(isValidDate2(Date5)); // Output: false
// Month can't be more than 12
console.log(isValidDate2(Date6)); // Output: false
console.log(isValidDate2(Date7)); // Output: true
// Month should have 2 digits
console.log(isValidDate2(Date8)); // Output: false
Outputfalse
true
false
true
false
false
true
false
In this approach, we are using instanceof operator which makes an instance of a date and if it is a valid date object then it will return true else it will return false. The !isNan() function can be used to determine whether the date in the Date object is valid.
Syntax:
let gfg = objectName instanceof objectType
Example: It describes the string date validation using instance of the operator.
JavaScript
// Creating variable having different values
let str = "13/2019/jan";
let str1 = "2019/jan/13";
let str2 = "jan/13/2019";
let str3 = "13/13/2019";
// Function for validation of date
function isValidDate(str) {
let date = new Date(str);
let ans = (date instanceof Date) && !isNaN(date);
return ans;
}
// Printing out the result in console
console.log(isValidDate(str)); //true
console.log(isValidDate(str1)); //true
console.log(isValidDate(str2)); //true
//false : invalid daate format
console.log(isValidDate(str3));
Outputtrue
true
true
false
Regardless of the date format, the JavaScript code Object.prototype.toString.call(date) === '[object Date]' is frequently used to verify whether an object is an instance of the Date class. It return the date object if it is a valid date object and it is not NaN then it will true else it will return false.
Syntax:
obj.toString()
Example: It describes the string date validation using Object.prototype.toString.call() function.
JavaScript
// Function for validation of date format
function isValiDate(str) {
let date = new Date(str);
let ans =
Object.prototype.toString.call(date) === "[object Date]"
&& !isNaN(date);
return ans;
}
// DD-MM-YYYY
let str = "13-jan-2019";
// MM-DD-YY
let str1 = "jan-19-13";
// DD-YY-MM
let str2 = "13-19-jan";
// DD/YY/MM
let str3 = "13/19/jan";
// DD/YY/MM (month in number)
let str4 = "13/19/01";
console.log(isValiDate(str));
console.log(isValiDate(str1));
console.log(isValiDate(str2));
console.log(isValiDate(str3));
console.log(isValiDate(str4));
Outputtrue
true
true
true
false
Approach 5: Using Moment.js Library
Moment.js is a javascript library which is used to validate the Date. It has a function "moment" which can two aruments and it returns true if the date argument matches to the formate arument else it will return false.
Syntax :
moment(date , format).isValid();
OR
moment(date: String).isValid()
Example: This describes how to validate string date format using moment library in JavaScript.
JavaScript
// Importing moment into js file
const moment = require('moment');
// Function for validation of date format
function isValidDate(dateString, format) {
return moment(dateString, format, true).isValid();
}
let Date1 = "2023-04-15";
let Date2 = "15-04-2023";
// Displaying the output
// Output: true
console.log(isValidDate(Date1, "YYYY-MM-DD"));
// Output: false
console.log(isValidDate(Date2, "YYYY-MM-DD"));
Output
true
false
Similar Reads
How to Validate Number String in JavaScript ? Validating a number string in JavaScript involves ensuring that a given string represents a valid number. This typically includes checking for digits, optional signs (+/-), decimal points, and possibly exponent notation (e.g., "1.23e4"). We will use various methods to validate number strings in Java
2 min read
How to Format a Date in JavaScript? Here are different ways to format the date in JavaScript.1. Using the toDateString() MethodThe toDateString() method formats the date object into a human-readable format as Day Month Date Year.SyntaxdateObj.toDateString();JavaScriptconst date = new Date(); const formatDate = date.toDateString(); con
2 min read
How to Validate Decimal Numbers in JavaScript ? Validating user input is an essential aspect of Web Development. As a developer, when we are playing with the numeric inputs provided by the end-user, it is quite important to ensure that the input provided by the user is in the correct format. We can use the regular expression to Validate Decimal N
2 min read
How to get tomorrow's date in a string format in JavaScript ? In this article, we will see how to print tomorrow's date in string representation using JavaScript. To achieve this, we use the Date object and create an instance of it. After that by using the setDate() method, we increase one date to the present date. Now by using the getDate() method you will ge
2 min read
How to Validate a Date in ReactJS? Validating input Date in react ensures the correct date input. The valid date input is commonly used in case of calculating days, getting DOB for user data, and other operations etc.Prerequisites:React JSNode JS and NPMApproachTo validate a date in React we will use the validator npm package. Take t
2 min read
JavaScript - How to Validate Form Using Regular Expression? To validate a form in JavaScript, you can use Regular Expressions (RegExp) to ensure that user input follows the correct format. In this article, we'll explore how to validate common form fields such as email, phone number, and password using RegExp patterns.1. Validating an Email AddressOne of the
4 min read
JavaScript - Check if a String is a Valid IP Address Format An IP address is a unique identifier assigned to each device connected to a computer network that uses the Internet Protocol for communication. There are two common types of IP addresses: IPv4 and IPv6. In this article, weâll explore how to check if a string is a valid IP address format in JavaScrip
2 min read
How to check a date is valid or not using JavaScript? To check if a date is valid or not in JavaScript, we have to know all the valid formats of the date. For ex - "YYYY/DD/MM", "DD/MM/YYYY", and "YYYY-MM-DD", etc. We have a given date format and we need to check whether the given format is valid or not according to the official and acceptable date for
3 min read
How to extract date from a string in dd-mmm-yyyy format in JavaScript ? In this article, we will see how to extract date from a given string of format "dd-mmm-yyyy" in JavaScript. We have a string, and we want to extract the date format "dd-mmm-yyyy" from the string.Example:// Stringstr = "India got freedom on 15-Aug-1947"// Extracted date from given string in // "dd-mm
2 min read
How To Format JavaScript Date as yyyy-mm-dd? We use JavaScript built-in help methods from the Date class that help us to create a formatted version of the current date in the form of yyyy-mm-dd. These are the approaches used to format JavaScript date as yyyy-mm-dd.Table of ContentUsing the ISO String Method USing JavaScript Method1. Using the
2 min read