如何获得日期的有效正则表达式

如何获得日期的有效正则表达式

本文介绍了如何获得日期的有效正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在VS 2015中使用MVC 5.2应用程序,使用SQL Server 2016.



我有一个名为Assessment_Date的字段,在数据库中定义为varchar(10),不是日期,因为我只想处理日期而不是时间。



我想要求用户输入日期形式:mm / dd / yyyy



在我的部分课程中,我有以下与该领域相关的内容:



[RegularExpression(@/ ^ \\\ {2} \ / \\\ {2} \ / \d {4} $ /)]

public string Assessment_Date {get;组; }




并在编辑视图中,我有以下验证消息行:



@ Html.ValidationMessageFor(model => model.Assessment_Date,mm / dd / yyyy,new {@class =text-danger})



结果是它输入了我输入框中的所有内容,即使它是一个格式正确的日期,如01/02/2017。



我在上检查了RegularExpression []和RegularExpression允许正确格式化的日期,如上所述。



这个RegularExpression在MVC中失败的原因是什么?我在包含RegularExpression的引号之前放置了@符号;否则,它会抱怨无法识别的转义码。我也曾经使用RegularExpressions遇到过麻烦。是否有一些技巧让他们使用MVC?谢谢。



我尝试过:



RegularExpression格式化日期字符串为mm / dd / yyyy

见上文。

I have an MVC 5.2 app in VS 2015, working with SQL Server 2016.

I have a field called Assessment_Date, which is defined in the database as a varchar(10), not as a Date, as I only want to work with the date and not the time.

I want to require the users to enter a date in the form: mm/dd/yyyy

In my partial class, I have the following lines pertinent to this field:

[RegularExpression(@"/^\d{2}\/\d{2}\/\d{4}$/")]
public string Assessment_Date { get; set; }


and in the Edit view, I have the following validation message line:

@Html.ValidationMessageFor(model => model.Assessment_Date, "mm/dd/yyyy", new { @class = "text-danger" })

The result is that it fails everything I type into the box, even if it's a correctly formatted date, like 01/02/2017.

I checked the RegularExpression on Online regex tester and debugger: PHP, PCRE, Python, Golang and JavaScript[^] and the RegularExpression is allowing correctly-formatted dates like the one above.

What might be the reason why this RegularExpression is failing in MVC? I placed the @ sign before the quotes containing the RegularExpression; otherwise, it complains about unrecognized escape codes. I've had trouble in the past with RegularExpressions too. Is there some trick to getting them to work with MVC? Thanks.

What I have tried:

RegularExpression to format date string to mm/dd/yyyy
See above.

推荐答案


[RegularExpression(@"^\d{2}/\d{2}/\d{4}






以下是RegEx文档的链接:

[]

以下是帮助构建RegEx并调试它们的工具的链接:

]

[]

这个显示哟RegEx是一个很好的图表,它非常有助于理解RegEx的作用:

[]



Here is a link to RegEx documentation:
perlre - perldoc.perl.org[^]
Here is links to tools to help build RegEx and debug them:
.NET Regex Tester - Regex Storm[^]
Expresso Regular Expression Tool[^]
This one show you the RegEx as a nice graph which is really helpful to understand what is doing a RegEx:
Debuggex: Online visual regex tester. JavaScript, Python, and PCRE.[^]


这篇关于如何获得日期的有效正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 22:01