【问题标题】:Date validation in asp.net with c#使用 c# 在 asp.net 中进行日期验证
【发布时间】:2013-09-12 07:07:52
【问题描述】:

    DateTime startDate = DateTime.ParseExact(txtstart.Text, "MM/dd/yyyy", null);
    DateTime endDate = DateTime.ParseExact(txtend.Text, "MM/dd/yyyy", null);

    string n1 = DropDownList2.SelectedItem.Text;

    if (DropDownList1.SelectedItem.Text == "Membership")// here you can add selectedindex as well
    {
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ProjectConnectionString"].ToString());
        con.Open();
        SqlDataAdapter adapter = new SqlDataAdapter("select p.Name,m.* from Membership_det m INNER JOIN Personal_det p  ON m.FID= p.FID where m.updateDate  between @Start and @End and m.FID =" + n1 + "", con);
        adapter.SelectCommand.Parameters.Add("@Start", SqlDbType.Date).Value = startDate;
        adapter.SelectCommand.Parameters.Add("@End", SqlDbType.Date).Value = endDate;
        DataTable dt = new DataTable();
        adapter.Fill(dt);
        con.Close();
        GridView1.DataSource = dt;
        GridView1.DataBind();

        // you can use this datatable dt to get that items and use dt to bind the corresponding control.

    }

我需要日期验证码。它应该接受 mm/dd/yyyy 格式的日期,否则它应该给出错误消息

aspx代码如下所示

    <asp:TextBox ID="txtstart" runat="server" ></asp:TextBox>


    <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="Please Enter in the date in MM/dd/yyyy Format" ControlToValidate="txtstart"></asp:RequiredFieldValidator>

    <asp:Label ID="Label2" runat="server" Text="End Date:"></asp:Label>

    <asp:TextBox ID="txtend" runat="server" ></asp:TextBox>
 <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ErrorMessage="Please Enter in the date in MM/dd/yyyy Format" ControlToValidate="txtend"></asp:RequiredFieldValidator>    

它给出调试消息并直接进入代码..运行程序时出现错误..我只想在页面本身显示错误消息

【问题讨论】:

    标签: c# asp.net sql-server-2008 date datetime


    【解决方案1】:

    设置文本框 10 的 maxlength 属性,

    <asp:TextBox ID="txtvaliddate" runat="server" MaxLength="10"></asp:TextBox>
    
    <asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server"
                       ControlToValidate="txtvaliddate" ValidationExpression="^(([1-9])|(0[1-9])|(1[0-2]))\/((0[1-9])|([1-31]))\/((19|20)\d\d)$" Display="Dynamic" SetFocusOnError="true" ErrorMessage="invalid date">*</asp:RegularExpressionValidator>
    

    在 C# 中 如果需要指定要使用的日期格式,可以使用 DateTime.ParseExact (MSDN Article)

    string[] formats= { "MM/dd/yyyy" }
    DateTime dateTime = DateTime.ParseExact(txtstart.Text, formats, new CultureInfo("en-US"), DateTimeStyles.None);
    

    【讨论】:

    • @SainPradeepfor两个文本框我应该使用这个..?开始日期和结束日期..?
    • 如果您想同时检查两个文本框,那么您需要为每个文本框添加单独的正则表达式验证器。
    • 它可以工作,但在 c# 代码中 DateTime startDate = DateTime.ParseExact(txtstart.Text, "MM/dd/yyyy", null);它给出错误,因为 String 未被识别为有效的 DateTime。
    • DateTime startDate = DateTime.ParseExact(txtstart.Text, "MM/dd/yyyy", null);上面的这行给出了错误-->当给出错误的输入时,字符串未被识别为有效的日期时间......而不是给出错误消息......无效的日期
    • DateTime startDate = DateTime.ParseExact(txtstart.Text, "MM/dd/yyyy", null);
    【解决方案2】:

    总是建议使用日期选择器控件而不是手动输入 Ajax date control

    【讨论】:

      【解决方案3】:

      此处已显示的正则表达式将在客户端为您提供帮助,但您还需要在服务器端验证它们。

      此外,您应该使用 DateTime.TryParse 而不是 DateTime.ParseExact,因为如果出现问题,第二个会抛出异常。

      DateTime startDate; 
      DateTime endDate;
      
      if (DateTime.TryParse(txtstart.Text, out startDate) && DateTime.TryParse(txtend.Text, out endDate))
      {
           string n1 = DropDownList2.SelectedItem.Text;
      
           if (DropDownList1.SelectedItem.Text == "Membership")
           {
            SqlConnection con = new 
      SqlConnection(ConfigurationManager.ConnectionStrings["ProjectConnectionString"].ToString());
             con.Open();
            SqlDataAdapter adapter = new SqlDataAdapter("select p.Name,m.* from Membership_det m INNER JOIN Personal_det p  ON m.FID= p.FID where m.updateDate  between @Start and @End and m.FID =" + n1 + "", con);
            adapter.SelectCommand.Parameters.Add("@Start", SqlDbType.Date).Value = startDate;
            adapter.SelectCommand.Parameters.Add("@End", SqlDbType.Date).Value = endDate;
            DataTable dt = new DataTable();
            adapter.Fill(dt);
            con.Close();
            GridView1.DataSource = dt;
            GridView1.DataBind();                
            }
      }
      else
      { 
           //Show error message
      }
      

      我还将为 m.FID 参数的 SQL 查询添加另一个参数,就像您为 @Start 和 @End 添加的一样。这会使您的代码容易受到 SQL 注入的攻击。

      【讨论】:

        【解决方案4】:

        使用验证表达式

        ValidationExpression="(0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.](19|20)\d\d)"
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-10-27
          • 2015-06-22
          • 2016-10-11
          • 1970-01-01
          • 1970-01-01
          • 2019-03-22
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多