![]() |
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. Table of ContentWe will explore all the above methods along with their basic implementation with the help of examples. Approach 1: Using the Date.parse() Inbuild FunctionIn 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.
Output true false Approach 2: Using Regular ExpressionFor 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:
Syntax: // Format 1: "YYYY-MM-DD" Example: It describes the string date validation using regular expressions in different ways.
Output false true false true false false true false Approach 3: Using Instanceof OperatorIn 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.
Output true true true false Approach 4: Using Object.prototype.toString.call() MethodRegardless 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.
Output true true true true false Approach 5: Using Moment.js LibraryMoment.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.
Output true |
Reffered: https://www.geeksforgeeks.org
JavaScript |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 12 |