Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regular expression to validate datetime format (MM/DD/YYYY) [duplicate]

I am trying to validate datetime format MM/DD/YYYY. Here is the code I am trying please help.

 function ValidateDate(testdate) {         var Status         var reg = /^(((0[1-9]|[12]\d|3[01])\/(0[13578]|1[02])\/((19|[2-9]\d)\d{2}))|((0[1-9]|[12]\d|30)\/(0[13456789]|1[012])\/((19|[2-9]\d)\d{2}))|((0[1-9]|1\d|2[0-8])\/02\/((19|[2-9]\d)\d{2}))|(29\/02\/((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))))$/g;         if (!reg.test(testdate)) {             Status = false;         }         return Status;     } 
like image 987
Supreet Avatar asked Mar 04 '13 07:03

Supreet


People also ask

What is regular expression for date format dd mm yyyy?

For dd-mm-yyyy format, use ^(0[1-9]|[12][0-9]|3[01])[- /.] (0[1-9]|1[012])[- /.] (19|20)\d\d$. You can find additional variations of these regexes in RegexBuddy's library.

What is the regular expression for date format?

The regex matches on a date with the YYYY/MM/DD format and a "Date of birth:" or "Birthday:" prefix (Year min: 1900, Year max: 2020). For example: Date of birth: 1900/12/01.

How do you validate a date in YYYY MM DD format in Java?

DateValidator validator = new DateValidatorUsingDateFormat("MM/dd/yyyy"); assertTrue(validator. isValid("02/28/2019")); assertFalse(validator. isValid("02/30/2019"));


1 Answers

Try your regex with a tool like http://jsregex.com/ (There is many) or better, a unit test.

For a naive validation:

function validateDate(testdate) {     var date_regex = /^\d{2}\/\d{2}\/\d{4}$/ ;     return date_regex.test(testdate); } 

In your case, to validate (MM/DD/YYYY), with a year between 1900 and 2099, I'll write it like that:

function validateDate(testdate) {     var date_regex = /^(0[1-9]|1[0-2])\/(0[1-9]|1\d|2\d|3[01])\/(19|20)\d{2}$/ ;     return date_regex.test(testdate); } 
like image 50
noirbizarre Avatar answered Sep 30 '22 11:09

noirbizarre