Regular expression validator for Date(yyyy/MM/dd) or year(yyyy)

后端 未结 1 1670
旧时难觅i
旧时难觅i 2021-01-28 12:48

I want regular validation expression to validate that only year (yyyy) or date is entered (yyyy-MM-dd).

It must not accept:

21,
23323

相关标签:
1条回答
  • 2021-01-28 13:44

    You don't need to use regex for that.

    I would use DateTime.TryParseExact overload that takes string[] as a parameter.

    string s = "2012";
    DateTime dt;
    var formats = new[] {"yyyy", "yyyy-MM-dd"};
    if(DateTime.TryParseExact(s, formats, CultureInfo.InvariantCulture,
                              DateTimeStyles.None, out dt))
    {
        // Your string is a valid DateTime for yyyy or yyyy-MM-dd format.
    }
    

    You said yyyy-MM-dd in your question but you said yyyy/MM/dd in your title. Add them to your formats array which one you try to validate.

    0 讨论(0)
提交回复
热议问题