简体   繁体   English

使用C#在ASP.NET中进行日期验证

[英]Date validation in asp.net with c#

显示错误的页面

    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.

    }

I need date validation code.. It should accept the date in the format mm/dd/yyyy or else it should give error message 我需要日期验证代码。它应接受格式为mm / dd / yyyy的日期,否则应给出错误消息

The aspx code is shown below 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>    

It gives the debug message and straightly goes to the code..wehn the error appears while running the program..I just want to display a error message in the page itself 它给出调试消息,然后直接转到代码。.运行程序时出现错误..我只想在页面本身中显示错误消息

Set maxlength property of your textbox 10, 设置文本框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>

in c# If you need to specify which date format you want to use, you would use DateTime.ParseExact (MSDN Article ) 在c#中,如果需要指定要使用的日期格式,则可以使用DateTime.ParseExact(MSDN Article

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

始终建议使用日期选择器控件,而不是手动输入Ajax日期控件

使用验证表达式

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

Regular expressions that are already shown here will help you on the client side but you also need to validate these on the server side. 这里已经显示的正则表达式将在客户端上为您提供帮助,但您还需要在服务器端对其进行验证。

Also, you should use DateTime.TryParse instead of DateTime.ParseExact because second one will throw exception if something is not ok. 另外,您应该使用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
}

I'd also add another parameter to your SQL query for m.FID parameter just like you added for @Start and @End. 我还将在m.FID参数的SQL查询中添加另一个参数,就像为@Start和@End添加的一样。 This makes your code vulnerable to SQL injection. 这使您的代码容易受到SQL注入的攻击。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM