2013年11月1日 星期五

自訂檢查日期欄位格式

自訂檢查日期欄位格式

.aspx

  1. <form id="form1" runat="server">
  2.  
  3.     <div>
  4.  
  5.         <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
  6.  
  7.         <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="送出" />
  8.  
  9.          <asp:CustomValidator ID="CustomValidator1" runat="server"
  10.  
  11.              ControlToValidate="TextBox1" ErrorMessage="CustomValidator"
  12.  
  13.              onservervalidate="CustomValidator1_ServerValidate" ValidateEmptyText="True"></asp:CustomValidator>
  14.  
  15.     </div>
  16.  
  17.     </form>
  18.  


.cs

  1. using System;
  2.  
  3. using System.Collections.Generic;
  4.  
  5. using System.Linq;
  6.  
  7. using System.Web;
  8.  
  9. using System.Web.UI;
  10.  
  11. using System.Web.UI.WebControls;
  12.  
  13.  
  14.  
  15. public partial class Test_tsValidatorDate : System.Web.UI.Page
  16.  
  17. {
  18.  
  19.     protected void Page_Load(object sender, EventArgs e)
  20.  
  21.     {
  22.  
  23.  
  24.  
  25.     }
  26.  
  27.     protected void Button1_Click(object sender, EventArgs e)
  28.  
  29.      {
  30.  
  31.          if (CustomValidator1.IsValid)
  32.  
  33.          {
  34.  
  35.              Response.Write("送出成功!");
  36.  
  37.          }
  38.  
  39.      }
  40.  
  41.      protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
  42.  
  43.      {
  44.  
  45.          DateTime dt;
  46.  
  47.  
  48.  
  49.          if (string.IsNullOrEmpty(args.Value))
  50.  
  51.          {
  52.  
  53.              CustomValidator1.ErrorMessage = "該欄位必填";
  54.  
  55.              args.IsValid = false;
  56.  
  57.          }
  58.  
  59.  
  60.  
  61.          else if (DateTime.TryParseExact(args.Value, "yyyy/MM/dd", null,System.Globalization.DateTimeStyles.AllowWhiteSpaces, out dt) == false)
  62.  
  63.          {
  64.  
  65.              CustomValidator1.ErrorMessage = "日期格式為 yyyy/MM/dd";
  66.  
  67.              args.IsValid = false;
  68.  
  69.          }
  70.  
  71.          else
  72.  
  73.          {
  74.  
  75.              args.IsValid = true;
  76.  
  77.          }
  78.  
  79.      }
  80.  
  81. }

沒有留言:

張貼留言