Date Regex Javascript Validator

Search...

⌘K

Date Regex Javascript Validator

Search...

⌘K


Date Regex Javascript Validator

Easily test and validate date formats like DD/MM/YYYY, MM-DD-YYYY, or ISO 8601 timestamps using the Date Regex JavaScript Validator. Whether you’re building forms, parsing logs, or cleaning data in JavaScript, this tool helps you ensure accurate and properly formatted dates. You can also try related tools like the JavaScript Regex Tester to experiment with patterns, or combine with the Email Regex JavaScript Validator and IP Address Regex JavaScript Validator to validate complete user data.

31-12-2024
Possible security issues
This regex appears to be safe.
Explanation
  • [A-Z]: uppercase letters
  • [a-z]: lowercase letters
  • [0-9]: digits
  • \.: a literal dot
  • +: one or more of the preceding
  • *: zero or more of the preceding
  • ?: optional (zero or one)
  • ^: start of string
  • $: end of string
Test your APIs today!

Write in plain English — Qodex turns it into secure, ready-to-run tests.

Regular Expression - Documentation

What is a Date Regex?


In JavaScript, a regular expression (regex) for dates helps identify and validate if a string matches a specific date format. Whether you’re building forms, data filters, or logs, validating dates ensures users input data correctly and prevents downstream errors.


A date regex can match patterns like:

  • DD/MM/YYYY

  • MM-DD-YYYY

  • YYYY-MM-DD

  • ISO 8601 timestamps like 2023-06-05T12:30:00Z


JavaScript Regex Pattern for Date Validation


Here’s a commonly used regex for basic DD/MM/YYYY validation:

/^(0[1-9]|[12][0-9]|3[01])[\/\-](0[1-9]|1[0-2])[\/\-](19|20)\d\d$/


Breakdown:

  • ^(0[1-9]|[12][0-9]|3[01]) – Validates the day (01–31)

  • [\/\-] – Matches / or - as a separator

  • (0[1-9]|1[0-2]) – Validates the month (01–12)

  • (19|20)\d\d$ – Validates the year (1900–2099)


How to Validate a Date Using Regex in JavaScript


Here’s a simple JavaScript code snippet using regex for date validation:

function isValidDate(dateString) {
  const dateRegex = /^(0[1-9]|[12][0-9]|3[01])[\/\-](0[1-9]|1[0-2])[\/\-](19|20)\d\d$/;
  return dateRegex.test(dateString);
}

console.log(isValidDate("25/12/2024")); // true
console.log(isValidDate("2024-12-25")); // false

Regex can be handy if you only want to check if a string matches a specific format, like or . However, keep in mind that even though you can use regex to check for the correct DD/MM/YYYY format, JavaScript's built-in Date constructor doesn't natively parse dates in this format. If you need to actually convert a DD/MM/YYYY string into a valid Date object, you'll need to reformat it to YYYY/MM/DD first.


Here’s a quick way to do this using split() and template literals:

let dateInput = "15/05/2019"; // DD/MM/YYYY format

let dateArray = dateInput.split("/");

let newDate = `${dateArray[2]}/${dateArray[1]}/${dateArray[0]}`;

console.log(newDate); // 2019/05/15 (YYYY/MM/DD)


Now you can safely use newDate with the JavaScript Date constructor:

let jsDate = new Date(newDate);
console.log(jsDate); // Outputs a valid Date object

This approach ensures your date strings are both validated and correctly parsed, so your code won’t trip over regional date formats.


How to Check if a String is a Valid Date in JavaScript


If you need to confirm both the format and the validity of the date itself, JavaScript’s built-in constructor and the function come to the rescue.

Here’s how you can do it:

function isDateValid(dateStr) {
  return !isNaN(new Date(dateStr));
}

// DD/MM/YYYY (not recognized by Date)
console.log(isDateValid("15/05/2019")); // false

// MM/DD/YYYY
console.log(isDateValid("05/15/2019")); // true

// YYYY/MM/DD
console.log(isDateValid("2019/05/15")); // true

Keep in mind:

  • The constructor understands formats like and , but not .

  • If the string doesn't represent a real date, will return an "Invalid Date" object, and will catch that.

When to Use Which Approach?

  • Regex validation is great for enforcing a specific input pattern.

  • Date object validation is better for checking if the date actually exists and is recognized by JavaScript.

Use both together for stricter validation: first check the format with regex, then confirm the date’s validity with the constructor.


Swapping Day and Year Positions in Date Strings


Need to convert a date string from DD/MM/YYYY to YYYY/MM/DD (or vice versa) in JavaScript? It's straightforward with a bit of string manipulation.

Simply split the original date string into its parts, rearrange the elements, and join them back together in the desired order. Here’s how you can go from DD/MM/YYYY to YYYY/MM/DD:

let originalDate = "15/05/2019"; // DD/MM/YYYY
let parts = originalDate.split("/");
// Rearranged to YYYY/MM/DD
let convertedDate = `${parts[2]}/${parts[1]}/${parts[0]}`;

console.log(convertedDate); // Outputs: 2019/05/15

Now, your convertedDate is ready to be used with JavaScript’s Date() constructor or for any format-specific needs. This simple swap ensures compatibility for common date transformations, especially when working across systems expecting different standards.


Convert a Date to DD/MM/YYYY Format in JavaScript


Let’s say you’ve received a JavaScript Date object or a valid date string and want to display it in the classic DD/MM/YYYY format (because “15/05/2024” just looks better than “2024-05-15”, right?). JavaScript’s Date methods can help, but you’ll need a bit of manual work.

Here’s a practical approach:

  1. Create a Date object — from a string like "2019/05/15" or from Date inputs.

  2. Check for a valid date using isNaN(), since invalid dates can sneak past the constructor.

  3. Extract day, month, and year ensuring each part is two digits (pad with a leading zero if needed).

function formatDateToDDMMYYYY(dateInput) {
  const dateObj = new Date(dateInput);
  if (isNaN(dateObj)) return "Invalid date"; // Guard against bad input

  let day = dateObj.getDate();
  let month = dateObj.getMonth() + 1; // Months are zero-indexed
  const year = dateObj.getFullYear();

  // Ensure day and month are always two digits
  day = day < 10 ? "0" + day : day;
  month = month < 10 ? "0" + month : month;

  return `${day}/${month}/${year}`;
}

// Example usage:
console.log(formatDateToDDMMYYYY("2019/05/15")); // "15/05/2019"


Heads up: The getMonth() method returns months zero-based—so January is 0, December is 11. That’s why we add 1 to get the correct display.

Now you’re ready to take any compatible date input and serve it up in European style.


Validating Dates with isNaN() in JavaScript


Regex is great for checking if a string matches a date format, but sometimes you want to be sure a value can really become a valid JavaScript Date object. That’s where isNaN() comes in handy.

You can use isNaN() in combination with new Date() to verify whether a date string actually results in a valid date:

function isDateValid(dateStr) {
  return !isNaN(new Date(dateStr));
}
  • If isNaN(new Date(dateStr)) returns false, your date string can be converted to a date.

  • If it returns true, JavaScript couldn’t make sense of the date—something’s off with your format or values.

Examples

console.log(isDateValid("15/05/2019")); // false (DD/MM/YYYY isn't recognized natively)
console.log(isDateValid("05/15/2019")); // true (MM/DD/YYYY is valid in JS)
console.log(isDateValid("2019/05/15")); // true (YYYY/MM/DD also valid)

Keep in mind: JavaScript’s Date constructor is picky about formats. Standard formats like MM/DD/YYYY or YYYY/MM/DD work out of the box, but others (like DD/MM/YYYY) may return false, even if they look “correct” to humans. A combo of regex and isNaN() lets you both check the format and confirm JavaScript actually accepts it.


Comparing Dates in JavaScript


Wondering how to check if one date comes before or after another in JavaScript? Thankfully, the language makes date comparisons refreshingly straightforward. You can directly compare two Date objects using standard comparison operators:

const firstDate = new Date('2024-06-01');
const secondDate = new Date('2024-06-05');

console.log(firstDate < secondDate); // true
console.log(firstDate > secondDate); // false


Under the hood, JavaScript converts the Date objects to numeric values representing milliseconds since January 1, 1970. So, comparison operators like <, >, <=, and >= work out of the box—no extra parsing or value extraction required.

If you need to check for equality, use the .getTime() method to compare the underlying timestamps:

console.log(firstDate.getTime() === secondDate.getTime()); // false

This approach keeps your code clean and avoids manual extraction of years, months, or days.


Try These Other Patterns:


ISO 8601 (e.g., 2024-06-05T12:30:00Z):

/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$/


MM-DD-YYYY Format:

/^(0[1-9]|1[0-2])[\-](0[1-9]|[12][0-9]|3[01])[\-](19|20)\d\d$/


Why Adjust the Month with getMonth() in JavaScript?


When using JavaScript’s getMonth() method, it’s important to remember that the method counts months from zero, not one—meaning January returns 0, February returns 1, and so on up to December, which returns 11. So, if you want your date string to display the usual 1–12 range for months, you need to add 1 to the value from getMonth().

For example, to format a date as MM-DD-YYYY, you’d write something like this:

const date = new Date();
const month = String(date.getMonth() + 1).padStart(2, '0');
const day = String(date.getDate()).padStart(2, '0');
const year = date.getFullYear();
const formattedDate = `${month}-${day}-${year}`;

Padding single-digit days or months with a leading zero ensures your output stays consistent (e.g., 04-07-2024 instead of 4-7-2024). This is especially useful for regex validation, as many patterns expect two-digit months and days.


What Happens with Invalid Dates in the JavaScript Date Constructor?


Handing an invalid date string to JavaScript’s Date constructor doesn’t throw an error—instead, it quietly creates an Invalid Date object. For example, try this:

const dateStr = "2019/15/15"; // Month 15 doesn’t exist!
Const parsedDate = new Date(dateStr);
console.log(parsedDate); // Outputs: Invalid Date

If you spot Invalid Date in your application’s output, it usually means the date string didn’t match a recognizable pattern or had impossible values (like a 15th month or 32nd day). Always validate your input before handing it to the Date constructor to avoid these sneaky surprises!


How to Tell If a Date Is in the Past or the Future with JavaScript?


Sometimes, you don't just want to validate a date format—you need to know if a given date has already happened or is still upcoming. Thankfully, JavaScript makes this comparison refreshingly straightforward.

All you need to do is:

  1. Create a JavaScript Date object from your input.

  2. Create another Date object set to the current date and time.

  3. Use the < or > operators to compare the two.

Here’s what that looks like in action:

const inputDate = new Date('2023-08-20'); // Date you want to check
const today = new Date(); // Current date and time

if (inputDate < today) {
  console.log('The input date is in the past.');
} else {
  console.log('The input date is in the future.');
}

No need to split strings or manually compare year, month, and day! JavaScript’s Date objects know how to compare themselves directly, so you get an accurate result every time.


Real-World Use Cases


  • Form Validation: Ensure users input valid birthdates, booking dates, or deadlines in forms.

  • Log Parsing: Extract valid date strings from server logs using the JavaScript Regex Tester.

  • Data Cleaning: Use this validator to scrub and standardize date formats in JavaScript-based data processing tools.


Combine With These Tools



Pro Tips


  • Use String.prototype.match() or .test() for fast regex checks in JavaScript.

  • Always validate date logic separately (e.g., 30 Feb is invalid even if the regex allows it).

  • Stick to ISO 8601 for APIs and database consistency.

  • Use non-capturing groups (like (?:...)) when you don’t need to extract parts of the match.

  • For performance, compile the regex once and reuse across your validation functions.


Frequently asked questions

Can JavaScript regex detect invalid dates like 31/02/2023?×
No, regex checks format only. You’ll need to combine it with logical date validation in JavaScript.
Should I use slash or dash separators in date regex?+
Can I validate ISO timestamps with regex?+
Is this regex reusable in backend systems like Node.js?+
Can I use this tool to test date regex patterns for other formats?+

Date Regex Javascript Validator

Search...

⌘K

Date Regex Javascript Validator

Search...

⌘K


Date Regex Javascript Validator

Date Regex Javascript Validator

Easily test and validate date formats like DD/MM/YYYY, MM-DD-YYYY, or ISO 8601 timestamps using the Date Regex JavaScript Validator. Whether you’re building forms, parsing logs, or cleaning data in JavaScript, this tool helps you ensure accurate and properly formatted dates. You can also try related tools like the JavaScript Regex Tester to experiment with patterns, or combine with the Email Regex JavaScript Validator and IP Address Regex JavaScript Validator to validate complete user data.

31-12-2024
Possible security issues
This regex appears to be safe.
Explanation
  • [A-Z]: uppercase letters
  • [a-z]: lowercase letters
  • [0-9]: digits
  • \.: a literal dot
  • +: one or more of the preceding
  • *: zero or more of the preceding
  • ?: optional (zero or one)
  • ^: start of string
  • $: end of string
Test your APIs today!

Write in plain English — Qodex turns it into secure, ready-to-run tests.

Regular Expression - Documentation

What is a Date Regex?


In JavaScript, a regular expression (regex) for dates helps identify and validate if a string matches a specific date format. Whether you’re building forms, data filters, or logs, validating dates ensures users input data correctly and prevents downstream errors.


A date regex can match patterns like:

  • DD/MM/YYYY

  • MM-DD-YYYY

  • YYYY-MM-DD

  • ISO 8601 timestamps like 2023-06-05T12:30:00Z


JavaScript Regex Pattern for Date Validation


Here’s a commonly used regex for basic DD/MM/YYYY validation:

/^(0[1-9]|[12][0-9]|3[01])[\/\-](0[1-9]|1[0-2])[\/\-](19|20)\d\d$/


Breakdown:

  • ^(0[1-9]|[12][0-9]|3[01]) – Validates the day (01–31)

  • [\/\-] – Matches / or - as a separator

  • (0[1-9]|1[0-2]) – Validates the month (01–12)

  • (19|20)\d\d$ – Validates the year (1900–2099)


How to Validate a Date Using Regex in JavaScript


Here’s a simple JavaScript code snippet using regex for date validation:

function isValidDate(dateString) {
  const dateRegex = /^(0[1-9]|[12][0-9]|3[01])[\/\-](0[1-9]|1[0-2])[\/\-](19|20)\d\d$/;
  return dateRegex.test(dateString);
}

console.log(isValidDate("25/12/2024")); // true
console.log(isValidDate("2024-12-25")); // false

Regex can be handy if you only want to check if a string matches a specific format, like or . However, keep in mind that even though you can use regex to check for the correct DD/MM/YYYY format, JavaScript's built-in Date constructor doesn't natively parse dates in this format. If you need to actually convert a DD/MM/YYYY string into a valid Date object, you'll need to reformat it to YYYY/MM/DD first.


Here’s a quick way to do this using split() and template literals:

let dateInput = "15/05/2019"; // DD/MM/YYYY format

let dateArray = dateInput.split("/");

let newDate = `${dateArray[2]}/${dateArray[1]}/${dateArray[0]}`;

console.log(newDate); // 2019/05/15 (YYYY/MM/DD)


Now you can safely use newDate with the JavaScript Date constructor:

let jsDate = new Date(newDate);
console.log(jsDate); // Outputs a valid Date object

This approach ensures your date strings are both validated and correctly parsed, so your code won’t trip over regional date formats.


How to Check if a String is a Valid Date in JavaScript


If you need to confirm both the format and the validity of the date itself, JavaScript’s built-in constructor and the function come to the rescue.

Here’s how you can do it:

function isDateValid(dateStr) {
  return !isNaN(new Date(dateStr));
}

// DD/MM/YYYY (not recognized by Date)
console.log(isDateValid("15/05/2019")); // false

// MM/DD/YYYY
console.log(isDateValid("05/15/2019")); // true

// YYYY/MM/DD
console.log(isDateValid("2019/05/15")); // true

Keep in mind:

  • The constructor understands formats like and , but not .

  • If the string doesn't represent a real date, will return an "Invalid Date" object, and will catch that.

When to Use Which Approach?

  • Regex validation is great for enforcing a specific input pattern.

  • Date object validation is better for checking if the date actually exists and is recognized by JavaScript.

Use both together for stricter validation: first check the format with regex, then confirm the date’s validity with the constructor.


Swapping Day and Year Positions in Date Strings


Need to convert a date string from DD/MM/YYYY to YYYY/MM/DD (or vice versa) in JavaScript? It's straightforward with a bit of string manipulation.

Simply split the original date string into its parts, rearrange the elements, and join them back together in the desired order. Here’s how you can go from DD/MM/YYYY to YYYY/MM/DD:

let originalDate = "15/05/2019"; // DD/MM/YYYY
let parts = originalDate.split("/");
// Rearranged to YYYY/MM/DD
let convertedDate = `${parts[2]}/${parts[1]}/${parts[0]}`;

console.log(convertedDate); // Outputs: 2019/05/15

Now, your convertedDate is ready to be used with JavaScript’s Date() constructor or for any format-specific needs. This simple swap ensures compatibility for common date transformations, especially when working across systems expecting different standards.


Convert a Date to DD/MM/YYYY Format in JavaScript


Let’s say you’ve received a JavaScript Date object or a valid date string and want to display it in the classic DD/MM/YYYY format (because “15/05/2024” just looks better than “2024-05-15”, right?). JavaScript’s Date methods can help, but you’ll need a bit of manual work.

Here’s a practical approach:

  1. Create a Date object — from a string like "2019/05/15" or from Date inputs.

  2. Check for a valid date using isNaN(), since invalid dates can sneak past the constructor.

  3. Extract day, month, and year ensuring each part is two digits (pad with a leading zero if needed).

function formatDateToDDMMYYYY(dateInput) {
  const dateObj = new Date(dateInput);
  if (isNaN(dateObj)) return "Invalid date"; // Guard against bad input

  let day = dateObj.getDate();
  let month = dateObj.getMonth() + 1; // Months are zero-indexed
  const year = dateObj.getFullYear();

  // Ensure day and month are always two digits
  day = day < 10 ? "0" + day : day;
  month = month < 10 ? "0" + month : month;

  return `${day}/${month}/${year}`;
}

// Example usage:
console.log(formatDateToDDMMYYYY("2019/05/15")); // "15/05/2019"


Heads up: The getMonth() method returns months zero-based—so January is 0, December is 11. That’s why we add 1 to get the correct display.

Now you’re ready to take any compatible date input and serve it up in European style.


Validating Dates with isNaN() in JavaScript


Regex is great for checking if a string matches a date format, but sometimes you want to be sure a value can really become a valid JavaScript Date object. That’s where isNaN() comes in handy.

You can use isNaN() in combination with new Date() to verify whether a date string actually results in a valid date:

function isDateValid(dateStr) {
  return !isNaN(new Date(dateStr));
}
  • If isNaN(new Date(dateStr)) returns false, your date string can be converted to a date.

  • If it returns true, JavaScript couldn’t make sense of the date—something’s off with your format or values.

Examples

console.log(isDateValid("15/05/2019")); // false (DD/MM/YYYY isn't recognized natively)
console.log(isDateValid("05/15/2019")); // true (MM/DD/YYYY is valid in JS)
console.log(isDateValid("2019/05/15")); // true (YYYY/MM/DD also valid)

Keep in mind: JavaScript’s Date constructor is picky about formats. Standard formats like MM/DD/YYYY or YYYY/MM/DD work out of the box, but others (like DD/MM/YYYY) may return false, even if they look “correct” to humans. A combo of regex and isNaN() lets you both check the format and confirm JavaScript actually accepts it.


Comparing Dates in JavaScript


Wondering how to check if one date comes before or after another in JavaScript? Thankfully, the language makes date comparisons refreshingly straightforward. You can directly compare two Date objects using standard comparison operators:

const firstDate = new Date('2024-06-01');
const secondDate = new Date('2024-06-05');

console.log(firstDate < secondDate); // true
console.log(firstDate > secondDate); // false


Under the hood, JavaScript converts the Date objects to numeric values representing milliseconds since January 1, 1970. So, comparison operators like <, >, <=, and >= work out of the box—no extra parsing or value extraction required.

If you need to check for equality, use the .getTime() method to compare the underlying timestamps:

console.log(firstDate.getTime() === secondDate.getTime()); // false

This approach keeps your code clean and avoids manual extraction of years, months, or days.


Try These Other Patterns:


ISO 8601 (e.g., 2024-06-05T12:30:00Z):

/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$/


MM-DD-YYYY Format:

/^(0[1-9]|1[0-2])[\-](0[1-9]|[12][0-9]|3[01])[\-](19|20)\d\d$/


Why Adjust the Month with getMonth() in JavaScript?


When using JavaScript’s getMonth() method, it’s important to remember that the method counts months from zero, not one—meaning January returns 0, February returns 1, and so on up to December, which returns 11. So, if you want your date string to display the usual 1–12 range for months, you need to add 1 to the value from getMonth().

For example, to format a date as MM-DD-YYYY, you’d write something like this:

const date = new Date();
const month = String(date.getMonth() + 1).padStart(2, '0');
const day = String(date.getDate()).padStart(2, '0');
const year = date.getFullYear();
const formattedDate = `${month}-${day}-${year}`;

Padding single-digit days or months with a leading zero ensures your output stays consistent (e.g., 04-07-2024 instead of 4-7-2024). This is especially useful for regex validation, as many patterns expect two-digit months and days.


What Happens with Invalid Dates in the JavaScript Date Constructor?


Handing an invalid date string to JavaScript’s Date constructor doesn’t throw an error—instead, it quietly creates an Invalid Date object. For example, try this:

const dateStr = "2019/15/15"; // Month 15 doesn’t exist!
Const parsedDate = new Date(dateStr);
console.log(parsedDate); // Outputs: Invalid Date

If you spot Invalid Date in your application’s output, it usually means the date string didn’t match a recognizable pattern or had impossible values (like a 15th month or 32nd day). Always validate your input before handing it to the Date constructor to avoid these sneaky surprises!


How to Tell If a Date Is in the Past or the Future with JavaScript?


Sometimes, you don't just want to validate a date format—you need to know if a given date has already happened or is still upcoming. Thankfully, JavaScript makes this comparison refreshingly straightforward.

All you need to do is:

  1. Create a JavaScript Date object from your input.

  2. Create another Date object set to the current date and time.

  3. Use the < or > operators to compare the two.

Here’s what that looks like in action:

const inputDate = new Date('2023-08-20'); // Date you want to check
const today = new Date(); // Current date and time

if (inputDate < today) {
  console.log('The input date is in the past.');
} else {
  console.log('The input date is in the future.');
}

No need to split strings or manually compare year, month, and day! JavaScript’s Date objects know how to compare themselves directly, so you get an accurate result every time.


Real-World Use Cases


  • Form Validation: Ensure users input valid birthdates, booking dates, or deadlines in forms.

  • Log Parsing: Extract valid date strings from server logs using the JavaScript Regex Tester.

  • Data Cleaning: Use this validator to scrub and standardize date formats in JavaScript-based data processing tools.


Combine With These Tools



Pro Tips


  • Use String.prototype.match() or .test() for fast regex checks in JavaScript.

  • Always validate date logic separately (e.g., 30 Feb is invalid even if the regex allows it).

  • Stick to ISO 8601 for APIs and database consistency.

  • Use non-capturing groups (like (?:...)) when you don’t need to extract parts of the match.

  • For performance, compile the regex once and reuse across your validation functions.


Frequently asked questions

Can JavaScript regex detect invalid dates like 31/02/2023?×
No, regex checks format only. You’ll need to combine it with logical date validation in JavaScript.
Should I use slash or dash separators in date regex?+
Can I validate ISO timestamps with regex?+
Is this regex reusable in backend systems like Node.js?+
Can I use this tool to test date regex patterns for other formats?+