How to useRegular Expressions in Javascript

  • Define a regular expression that matches the required date format(s).
  • Validate the date string against the regular expression.
  • Create a Date object and further check if the date is valid.
  • This approach ensures that the date string is in the correct format before further validation.

Example: Let’s consider we want to validate dates in the formats YYYY-MM-DD, DD/MM/YYYY, and MM-DD-YYYY.

JavaScript
function isValidDateFormat(dateString, format) {
    let regex;

    // Define regex patterns for different date formats
    switch (format) {
        case 'YYYY-MM-DD':
            regex = /^\d{4}-\d{2}-\d{2}$/;
            break;
        case 'DD/MM/YYYY':
            regex = /^\d{2}\/\d{2}\/\d{4}$/;
            break;
        case 'MM-DD-YYYY':
            regex = /^\d{2}-\d{2}-\d{4}$/;
            break;
        default:
            return false; // Unsupported format
    }

    // Check if dateString matches the regex
    if (!regex.test(dateString)) {
        return false;
    }

    // Parse the date parts based on the format
    let parts;
    let day, month, year;

    switch (format) {
        case 'YYYY-MM-DD':
            parts = dateString.split('-');
            year = parseInt(parts[0], 10);
            month = parseInt(parts[1], 10) - 1; // months are 0-based in JS
            day = parseInt(parts[2], 10);
            break;
        case 'DD/MM/YYYY':
            parts = dateString.split('/');
            day = parseInt(parts[0], 10);
            month = parseInt(parts[1], 10) - 1;
            year = parseInt(parts[2], 10);
            break;
        case 'MM-DD-YYYY':
            parts = dateString.split('-');
            month = parseInt(parts[0], 10) - 1;
            day = parseInt(parts[1], 10);
            year = parseInt(parts[2], 10);
            break;
    }

    // Create a Date object
    const date = new Date(year, month, day);

    // Check if the Date object represents the correct date
    if (date.getFullYear() !== year || date.getMonth() !== month || date.getDate() !== day) {
        return false;
    }

    return true;
}

// Example usage:
console.log(isValidDateFormat('2024-05-24', 'YYYY-MM-DD')); // true
console.log(isValidDateFormat('24/05/2024', 'DD/MM/YYYY')); // true
console.log(isValidDateFormat('05-24-2024', 'MM-DD-YYYY')); // true
console.log(isValidDateFormat('2024/05/24', 'YYYY-MM-DD')); // false

Output
true
true
true
false


JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples.



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 e.g.”YYYY/DD/MM”,”DD/MM/YYYY”, and “YYYY-MM-DD”, etc. we will have a given date format and we need to check whether that given format is valid or not according to the official and acceptable date format.

There are two methods to solve this problem which are discussed below: 

Table of Content

  • Approach 1: Using Custom Method
  • Approach 2: Using isNan() Method
  • Approach 3: Using Regular Expressions

Similar Reads

Approach 1: Using Custom Method

Store the date object in a variable.If the date is valid then the getTime() will always be equal to itself.If the date is Invalid then the getTime() will return NaN which is not equal to itself.The isValid() function is used to check whether the getTime() method is equal to itself....

Approach 2: Using isNan() Method

Store the date object into a variable date.Check if the variable date is created by Date object or not by using Object.prototype.toString.call(d) method.If the date is valid then the getTime() method will always be equal to itself.If the date is Invalid then the getTime() method will return NaN which is not equal to itself.In this example, isValid() method is checking if the getTime() is equal to itself or not....

Approach 3: Using Regular Expressions

Define a regular expression that matches the required date format(s).Validate the date string against the regular expression.Create a Date object and further check if the date is valid.This approach ensures that the date string is in the correct format before further validation....