Karthik G
Karthik G

Reputation: 1262

Date validator/format

I am trying to validate the format of date and also validate the date equal to or less than today in C# I am trying to achieve this in c# using regular expressions.

The formats I am trying to support are dd/mm/yyyy, dd-mm-yyyy, yyyy-mm-dd, yyyy/mm/dd.

var expressions = new List<Regex>();

expressions.Add(new Regex("^\\d{4}-((0\\d)|(1[012]))-(([012]\\d)|3[01])$"));
expressions.Add(new Regex("(((0|1)[1-9]|2[1-9]|3[0-1])\\/(0[1-9]|1[0-2])\\/((19|20)\\d\\d))$"));

return expressions;

Can somone please tell me what i am doing wrong in my reg ex and also suggest a better way to achieve this.

Upvotes: 1

Views: 1167

Answers (2)

Ian
Ian

Reputation: 30813

There are a couple of problems here.

  1. Your regular expression here

    "^\\d{4}-((0\\d)|(1[012]))-(([012]\\d)|3[01])$"
    

    Can only find date format with -, not with / (that is 1999-12-25 is valid but 1997/11/15 is not). If you want to change it, you should use

    "\\d{4}(-|\/)((0\\d)|(1[012]))(-|\/)(([012]\\d)|3[01])$" //^ removed, \/ added
    

    Which would match both 1999-12-25 and 1997/11/15 (edit: but will also match 1998/05-28!)

  2. Likewise, your regular expression here

    "(((0|1)[1-9]|2[1-9]|3[0-1])\\/(0[1-9]|1[0-2])\\/((19|20)\\d\\d))$"
    

    Can only match 12/11/1954 but cannot match 12-11-1954. Some more, because you put (0|1)[1-9]|2[1-9], your regex cannot match 10-11-1954. Use

    "((0|1)[0-9]|2[0-9]|3[0-1])(-|\/)(0[1-9]|1[0-2])(-|\/)(19|20)\\d\\d$"
    

instead

But seriously, unless is a must, it is a hellish task to parse (not to say to compare) DateTime value with Regex! You should just use DateTime.TryParse or DateTime.Parse together with TimeSpan for parsing and for comparison respectively.

Upvotes: 2

drf
drf

Reputation: 8699

There is no need to use regular expressions for this; you can call DateTime.ParseExact or DateTime.TryParseExact with the permitted formats as an argument. Unlike regular expressions, this approach will also ensure that the user-provided date is valid (e.g., allowing "2016-02-29" but not "2015-02-29").

string inputDate = "2015-01-01";
DateTime dt;

bool validDate = DateTime.TryParseExact(inputDate,
    new[] { "dd/MM/yyyy", "dd-MM-yyyy", "yyyy-MM-dd", "yyyy/MM/dd" },
    CultureInfo.InvariantCulture, 
    DateTimeStyles.None,
    out dt);

Console.WriteLine(validDate ? dt.ToString("MM/dd/yyyy") : "Invalid date"); // 01/01/2015

Upvotes: 3

Related Questions