Regex for Date and time picker javascript(Resolved)

Viewed 367

I was trying to find regex for a date and time picker in JavaScript

https://i.stack.imgur.com/KQWgO.png

which format is hh/mm ampm and dd/mm/yyyy hh/mm ampm.

I tried ([0-3][0-9])([0][1-9]|[1][0-2])-\d{4} ( ([0-1][0-9]|[2][0-4]):[0-5][0-9]) but doesnt seem to work cuz / apparently is not a normal simbol.

What is the correct regular expresion? RegEx has always been hard for me

2 Answers

If those are the standard <input type="datetime" /> and variants thereof, then you should really do some basic debugging.

console.log(datetimeInput.value);
// 2020-08-17 23:33:05

Date and time inputs are displayed in the user's local format, but they are internally stored in the correct format. Furthermore, they are validated automatically by the browser, so there should be no need whatsoever to run a regex over them.

you try this one for date and time:

/^([0-9]{2}\/){2}\d{4}\s[0-2][0-9]\:[0-6][0-9]\s(pm|am)$/

and this one for time:

/^[0-2][0-9]\:[0-6][0-9]\s(pm|am)$/

const regex = /^([0-9]{2}\/){2}\d{4}\s[0-2][0-9]\:[0-6][0-9]\s(pm|am)$/;

const regex_time = /^[0-2][0-9]\:[0-6][0-9]\s(pm|am)$/;

console.log(regex.test("09/09/2020 12:60 pm"))
console.log(regex.test("09/09/2020 12:60 am"))
console.log(regex_time.test("12:60 am"))
console.log(regex_time.test("12:60 pm"))

Related