Hi Friends 👋,
Welcome To Infinitbility! ❤️
To validate date string using regex, use /^\d{2}[\/|\-]\d{2}[\/|\-]\d{4}$/
it will handle date.
This regex will validate string date should passing it to the Date constructor returns a valid Date object.
Let’s see short example of javascript regex for validate date.
const regex = /^\d{2}[\/|\-]\d{2}[\/|\-]\d{4}$/;
console.log(regex.test("09/30/2022"))
Today, I’m going to show you How do I check value contain valid date in javascript, as above mentioned, I’m going to use the above-mentioned regex with test()
method.
Let’s start today’s tutorial how do you check valid date in javascript using regex?
Here, I will show validate date in javascript and typescript.
Javascript regex for validate date example
Here, we will create common validate function where we will validate param should validate date.
function validate(param){
const regex = /^\d{2}[\/|\-]\d{2}[\/|\-]\d{4}$/;
return regex.test(param);
}
// validate mm/dd/yyyy
console.log(validate("09/30/2022"))
// true
// validate dd/mm/yyyy
console.log(validate("30/09/2022"))
// true
// validate mm-dd-yyyy
console.log(validate("09-30-2022"))
// true
// validate dd-mm-yyyy
console.log(validate("30-90-2022"))
// true
// validate yyyy/mm/dd
console.log(validate("2022/09/30"))
// false
// validate yyyy-mm-dd
console.log(validate("yyyy-mm-dd"))
// false
Output
Typescript regex for validate date example
Same like javascript, we will create a function and call it with diffrent parameters.
function validate(param: string){
const regex = /^\d{2}[\/|\-]\d{2}[\/|\-]\d{4}$/;
return regex.test(param);
}
// validate mm/dd/yyyy
console.log(validate("09/30/2022"))
// true
// validate dd/mm/yyyy
console.log(validate("30/09/2022"))
// true
// validate mm-dd-yyyy
console.log(validate("09-30-2022"))
// true
// validate dd-mm-yyyy
console.log(validate("30-90-2022"))
// true
// validate yyyy/mm/dd
console.log(validate("2022/09/30"))
// false
// validate yyyy-mm-dd
console.log(validate("yyyy-mm-dd"))
// false
Output
I hope it helps you, All the best 👍.