1

I need to tweak a regular expression listed below to make sure the data is validate accordingly to this format:

01/23/2013 10:25

[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy HH:mm}")]

[RegularExpression("^(0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.](19|20)[0-9][0-9]$", ErrorMessage = "Invalid date")]

The current regular expression it seems does not take account of HH and MM

Could you please give me an hit? Thanks

GibboK
  • 71,848
  • 143
  • 435
  • 658
  • Why would you validate datetime using Regex? You are using wrong tool. Although it might work, but it clearly becomes complex and unreadable. You should better use `DateTime` parsers, appropriate in the language you are using. – Rohit Jain Jan 23 '13 at 09:38
  • Which tool do you suggest me? I need a straight forward solution to implement data annotation on a DateTime field in MVC 3 web app. – GibboK Jan 23 '13 at 09:39
  • @GibboK.. Well, I'm not the `DotNet` guy. So, can't tell you about any tool. But certainly you would find one by a little only search. – Rohit Jain Jan 23 '13 at 09:44

2 Answers2

1

For HH:mm, you can use this regex: -

(0[0-9]|1[0-9]|2[0-3]):(0[0-9]|[1-5][0-9])

So, adding it to your regex, it would become: -

"^(0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.](19|20)[0-9][0-9] (?:(0[0-9]|1[0-9]|2[0-3]):(0[0-9]|[1-5][0-9]))$"
Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
  • Thanks for your answer, unfortunately using your regex the validation fail with a date in this format 01/23/2013 10:38 what could be the problem? – GibboK Jan 23 '13 at 09:38
  • @GibboK. Sorry. I forgot to group the two parts of `HH:mm`. Now it would work. You can try it. – Rohit Jain Jan 23 '13 at 09:42
  • it seems that does not work, maybe the problem it is in some other place... anyway man thanks – GibboK Jan 23 '13 at 09:56
0

Have you tried this may be it will usefull for this case Try This

OR you should create your own validator (inherit BaseValidator) and use DateTime.TryParseExact to check that the value can be converted to DateTime.

Amol
  • 1,431
  • 2
  • 18
  • 32
  • have you seen [link](http://stackoverflow.com/questions/5565012/how-to-write-a-regex-for-mmddyyyyhhmmss) and [link](http://stackoverflow.com/questions/12717638/need-to-validate-mm-dd-yyyy-hhmm-tt-in-javascript) – Amol Jan 23 '13 at 10:50