正则表达式验证的日期(YYYY / MM / DD)或年份(YYYY) [英] Regular expression validator for Date(yyyy/MM/dd) or year(yyyy)

查看:2021
本文介绍了正则表达式验证的日期(YYYY / MM / DD)或年份(YYYY)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要定期验证表达式验证,只有一年(年)或日期输入(YYYY-MM-DD)

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

它不能接受:

21,
23323

应该接受任何四位数的整数值(比如2012),也应该接受一年(YYYY-MM-DD)格式。

It should accept any four digit integer value (say 2012) and it should also accept year (yyyy-MM-dd) format only.

推荐答案

您不需要使用正则表达式为

You don't need to use regex for that.

我会用的 DateTime.TryParseExact 超载这需要的String [] 作为参数。<​​/ p>

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.
}

您说 YYYY-MM-DD 在你的问题,但你说的 YYYY / MM / DD 在您的标题。将它们添加到您的格式阵列哪一个你尝试验证。

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.

这篇关于正则表达式验证的日期(YYYY / MM / DD)或年份(YYYY)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆