【发布时间】:2009-08-03 14:51:37
【问题描述】:
我有 3 个文本框字段。表示日期
例如 DD MM YYYY
我如何验证每个文本框中只输入了正确的数据。 是正则表达式吗??
我需要在 ascx/aspx 文件而不是 .cs 代码隐藏中执行此操作
谢谢
【问题讨论】:
-
您不能在一个文本框中输入日期是否有原因?这将使您的验证更加容易。
-
这些设计带有三个文本框:(
我有 3 个文本框字段。表示日期
例如 DD MM YYYY
我如何验证每个文本框中只输入了正确的数据。 是正则表达式吗??
我需要在 ascx/aspx 文件而不是 .cs 代码隐藏中执行此操作
谢谢
【问题讨论】:
您可以使用正则表达式验证每个字段,但它不会考虑具有不同天数的不同月份:您可以输入无效日期。
在服务器端,它可以通过以下方式进行验证:
DateTime D;
string CombinedDate=String.Format("{0}-{1}-{2}", YearField.Text, MonthField.Text, DayField.Text);
if(DateTime.TryParseExact(CombinedDate, "yyyy-M-d", DateTimeFormatInfo.InvariantInfo, DateTimeStyles.None, out D)) {
// valid
} else {
// not valid
}
【讨论】:
您应该使用CustomValidator 来验证所有 3 个控件的结果输入。也许在该自定义验证脚本中,您可以使用正则表达式来验证数据。
【讨论】:
尝试将它们放入 DateTime 对象中。
int day, month, year;
if (Int32.TryParse(dayInput.Value, out day)) {
if (Int32.TryParse(monthInput.Value, out month)) {
if (Int32.TryParse(yearInput.Value, out year)) {
DateTime birthDate = new DateTime(year, month, day);
if ([birthDate is in valid range])
// it passes
}
}
}
我知道这不是很优雅,但您也可以使用以下 RegEx 以同样的方式对其进行测试
[0-9]+
但是我喜欢我的方式,因为我可以将它输入到 DateTime 字段中,然后测试范围以确保它不超过当前日期并且不低于当前日期前 100 年。
【讨论】:
aspx文件中的验证不会在表示层中引入逻辑代码吗?
我建议使用 AJAX 控件(有一个 AJAX MaskEdit 框 - 类似)。他们通常对这类事情没问题,看看 AJAX 工具包,如果你部署的服务器可以支持这些。
【讨论】:
完整示例:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm2.aspx.cs" Inherits="Web_Layer.WebForm2" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<script runat="server">
protected void ValidateDate(object sender, EventArgs e)
{
int day=0;
int month=0;
int year=0;
if (!int.TryParse(txtDD.Text, out day))
day = 0;
if (!int.TryParse(txtMM.Text, out month))
month = 0;
if (!int.TryParse(txtYY.Text, out year))
year = 0;
if (((year > 0)) && ((month > 0) && (month < 13)) && ((day > 0) && (day <= DateTime.DaysInMonth(year, month))))
{
lblValid.Text = "Valid!";
}
else
{
lblValid.Text = "NOT Valid!";
}
}
</script>
<asp:TextBox ID="txtDD" runat="server"></asp:TextBox>
<asp:TextBox ID="txtMM" runat="server"></asp:TextBox>
<asp:TextBox ID="txtYY" runat="server"></asp:TextBox>
<asp:Button ID="btn" runat="server" OnClick="ValidateDate"/>
<asp:Label ID="lblValid" runat="server"></asp:Label>
</div>
</form>
</body>
</html>
【讨论】:
改用下拉菜单怎么样?
【讨论】:
public bool isValidDate(string datePart, string monthPart, string yearPart)
{
DateTime date;
string strDate = string.Format("{0}-{1}-{2}", datePart, monthPart, yearPart);
if (DateTime.TryParseExact(strDate, "dd-MM-yyyy", System.Globalization.DateTimeFormatInfo.InvariantInfo , System.Globalization.DateTimeStyles.None, out date ))
{
return true;
}
else
{
return false ;
}
}
【讨论】: