[英]validate 3 textfields representing date of birth
我有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 ;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.