1

Trying to create a regex for Date in this format dd.MM.yyyy.

I want to use it with a DataAnnotation, like this

[RegularExpression(@"<theregex>")]
public DateTime Date { get; set; }
rae1
  • 6,066
  • 4
  • 27
  • 48
Omu
  • 69,856
  • 92
  • 277
  • 407
  • Does it have to take into account invalid dates like 30.02.2010 and things like that or is it just something to pull out things that look like dates and you can then check them afterwards? – Chris Jul 01 '10 at 08:31
  • 8
    Why do you need a regex? Would it not be better to use `Date.ParseExact()`? – Rowland Shaw Jul 01 '10 at 08:31
  • 1
    @Rowland Shaw I use xVal which is generating rules for jquery.validation – Omu Jul 01 '10 at 08:33
  • It's smarter to use date.parse or yyyy.mm.dd. If someone from the u.s. saw that date format, they would try 02.30.2010... – simendsjo Jul 01 '10 at 08:36
  • 1
    @Rowland: Date.ParseExact() is no valid value for a data annotation. These need to be constant. – Jens Jul 01 '10 at 08:42
  • @Jens that wasn't mentioned up front – Rowland Shaw Jul 01 '10 at 09:11

5 Answers5

7

I suggest that regex is not exactly the best way to do this. You haven't given the context, so it's hard to guess what you're doing overall... but you might want to create a DateExpression attribute or such and then do:

return DateTime.ParseExact(value, "dd.MM.yyyy");

in wherever your converter is defined.

Noldorin
  • 144,213
  • 56
  • 264
  • 302
  • 1
    I tried your suggestion and I get `No overload for method 'ParseExact' takes 2 arguments` – sam Oct 01 '18 at 19:13
4
^(0[1-9]|[12][0-9]|3[01])[.](0[1-9]|1[012])[.](19|20)[0-9]{2}$

This regex matches 01.01.1900, 01.01.2000 but doesn't match 1.1.2000 or 1/1/00.

Julien Hoarau
  • 48,964
  • 20
  • 128
  • 117
1
[0-3]{0,1}[0-9]\.[0-1]{0,1}[0-9]\.[0-9]{4,2}

matches: 28.2.96, 1.11.2008 and 12.10.2005

M3t0r
  • 182
  • 9
1

Just because I always find this site useful, here is an online regex checker. On the right hand side it also has examples and community contributions. In there are a number of Date matching regex variations.

You can type in a load of dates you wish to match and try some of the different examples if you're not sure which is best for you. As with anything, there are multiple ways to solve the problem, but it might help you choose the one that fits best.

Ian
  • 33,605
  • 26
  • 118
  • 198
0
^(0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.](19|20)\d\d$ 

This one also accepts - and / as separators. You can remove them if you want.

Matteo Mosca
  • 7,380
  • 4
  • 44
  • 80