I want regular validation expression to validate that only year (yyyy) or date is entered (yyyy-MM-dd).
It must not accept:
21,
23323
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.