问题描述
大家好,
如何验证字符串中的日期.我需要服务器端验证.我想使用正则表达式来验证字符串或语句中的日期...请为该问题建议服务器端代码.
例如:"DOB:02-02-1987"或"DOB:1987年5月14日"
谢谢
Hi All,
How to validate the date within a string..?? I want the server-side validation.I want the regular expression to validate date within a string or statement...please suggest server side code for this question.
For ex:"DOB:02-02-1987" or "DOB:14th may 1987"
Thanks
推荐答案
function IsValidDate(dateString) {
return !isNaN(Date.parse(dateString));
}
在服务器端,您需要使用System.DateTime
方法Parse
或ParseExact
做同样的事情.与JavaScript不同,您需要以与所需区域性信息(IFormatProvider
)和/或格式说明符相对应的准确格式提供输入字符串.但是对于Parse
方法,有一些变体:仅日期,仅时间,两者,并且区域性应与当前线程区域性相对应.
此外,您需要在try-catch块中调用此类方法,因为它可以捕获异常.例如:
On server side, you need to do the same thing using System.DateTime
methods Parse
or ParseExact
. Unlike JavaScript, you will need to supply input string in exact format corresponding to required culture information (IFormatProvider
) and/or format specifiers; but for Parse
method, there are variants: date only, time only, both, and the culture should correspond current thread culture.
Besides, you need to call such method in the try-catch block as it can catch exception. For example:
static bool IsValidDate(string value) {
try {
System.DateTime.Parse(value);
return true;
} catch(System.FormatException) {
return false;
} //exception
} //IsValidDate
请参阅:
http://msdn.microsoft.com/en-us/library/system.datetime.aspx [ ^ ].
有关时间字符串格式,请参见:
http://msdn.microsoft.com/en-us/library/az4se3k1.aspx [ ^ ],
http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx [ ^ ].
Please see:
http://msdn.microsoft.com/en-us/library/system.datetime.aspx[^].
For time string formats, please see:
http://msdn.microsoft.com/en-us/library/az4se3k1.aspx[^],
http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx[^].
<asp:textbox id=""txtDateStart"" cssclass=""input"" runat=""server"" width=""200″" xmlns:asp="#unknown">
<asp:comparevalidator id=""cmprValidatorDateStart"" controltovalidate=""txtDateStart"" xmlns:asp="#unknown">
Type="Date" Display="Dynamic" Operator="DataTypeCheck"
ErrorMessage="*Not a valid date." runat="server"<>/asp:CompareValidator>
这篇关于用于验证字符串中日期的正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!