Asp.net 使用CompareValidator检查由3个下拉框组成的日期

Asp.net 使用CompareValidator检查由3个下拉框组成的日期,asp.net,vb.net,Asp.net,Vb.net,我有3个对应于日、月和年的投递箱。在用户选择日期后,我连接3个字符串并将其传递给数据库 我的问题是如何在将日期传递到数据库之前以交互方式验证该日期。是否要过滤掉6月31日或2月30日等不存在的无效日期 我想到了一个逃逸者。我要做的是创建两个隐藏文本框,一个用原始用户输入字符串填充,另一个用转换为日期的用户输入字符串填充(如果日期无效,我认为系统应将其转换为最接近的日期) 然后,我使用CompareValidator比较这些文本框,如果它们不匹配,将提示错误。然而,不知何故,它不起作用。有人知道为

我有3个对应于日、月和年的投递箱。在用户选择日期后,我连接3个字符串并将其传递给数据库

我的问题是如何在将日期传递到数据库之前以交互方式验证该日期。是否要过滤掉6月31日或2月30日等不存在的无效日期

我想到了一个逃逸者。我要做的是创建两个隐藏文本框,一个用原始用户输入字符串填充,另一个用转换为日期的用户输入字符串填充(如果日期无效,我认为系统应将其转换为最接近的日期)

然后,我使用CompareValidator比较这些文本框,如果它们不匹配,将提示错误。然而,不知何故,它不起作用。有人知道为什么吗。或者可能有人不太了解检查投递箱中日期的复杂技巧

如有任何意见或建议,我将不胜感激

前端代码:

<asp:DropDownList ID="Dates" runat="server" >
<asp:ListItem></asp:ListItem>
<asp:ListItem>01</asp:ListItem>
<asp:ListItem>02</asp:ListItem>
 <asp:ListItem>03</asp:ListItem>
.......
 <asp:ListItem>29</asp:ListItem>
<asp:ListItem>30</asp:ListItem>
 <asp:ListItem>31</asp:ListItem>
</asp:DropDownList>&nbsp;

<asp:DropDownList ID="Monthes" runat="server" >
<asp:ListItem></asp:ListItem>
<asp:ListItem>January</asp:ListItem>
                          .......
<asp:ListItem>December</asp:ListItem>
</asp:DropDownList>
&nbsp;

<asp:DropDownList ID="years" runat="server">
 <asp:ListItem></asp:ListItem>
</asp:DropDownList>

<asp:TextBox ID="UserInput" runat="server"></asp:TextBox>
<asp:TextBox ID="ConvertedInput" runat="server"></asp:TextBox>
<asp:CompareValidator ID="CompareValidator1" class="errorMess" runat="server" 
    ControlToCompare="UserInput" ControlToValidate="ConvertedInput" 
    ErrorMessage="Invalid Date"></asp:CompareValidator>
If Not Page.IsPostBack Then
        For count As Integer = 0 To 60
            years.Items.Add(CurYear - count)
        Next
    End If
    ConvertedInput.Visible = False
    UserInput.Visible = False


    .....

    Bday = years.Text & "-" & Monthes.Text & "-" & Dates.Text
    Dim TempDate As Date = CDate(Bday)
    Dim ConvDate As String = TempDate.ToString("yyyy-MM-dd")
    UserInput.Text = Bday
    ConvertedInput.Text = ConvDate

您可以使用
customvalidator
,生成日期并验证它是否有效。但是,我建议使用一个直接的文本框,并使用像jquery UI这样的UI库将文本框转换为日期选择器。然后可以使用
DateTime.TryParse()
从代码隐藏中的文本框中提取日期


最大的优点是只需要处理一个输入,而不需要字符串浓缩/格式化。

如果日期无效,我尝试DateTime.Parse()(实际上还有Cdate)时总是会出错。你知道如何使用自定义验证器吗?我也试过这个。但它也不起作用:
I如果我在框中键入,它就起作用了。如果我只是从后面填充它,它就不存在了。您使用比较验证器的方法是正确的。“从后面填充它”?什么意思?设置值是否代码隐藏?设置该值不会触发验证。这是通过调用
validate
完成的
DateTime.TryParse'string out DateTime)
DateTime.Parse(string)
不同。