.aspx
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="送出" />
<asp:CustomValidator ID="CustomValidator1" runat="server"
ControlToValidate="TextBox1" ErrorMessage="CustomValidator"
onservervalidate="CustomValidator1_ServerValidate" ValidateEmptyText="True"></asp:CustomValidator>
</div>
</form>
.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Test_tsValidatorDate : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
if (CustomValidator1.IsValid)
{
Response.Write("送出成功!");
}
}
protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
{
DateTime dt;
if (string.IsNullOrEmpty(args.Value))
{
CustomValidator1.ErrorMessage = "該欄位必填";
args.IsValid = false;
}
else if (DateTime.TryParseExact(args.Value, "yyyy/MM/dd", null,System.Globalization.DateTimeStyles.AllowWhiteSpaces, out dt) == false)
{
CustomValidator1.ErrorMessage = "日期格式為 yyyy/MM/dd";
args.IsValid = false;
}
else
{
args.IsValid = true;
}
}
}
沒有留言:
張貼留言