ASP.NET利用CustomValidator的ClientValidationFunction与OnServerValidate来double check资料输入的正确性...

最近网友问一个CustomValidator验证控制项的问题

后来发现这个CustomValidator有一個ClientValidationFunction

去找了msdn,才知道可以利用client端来验证输入的资料

一般资料的验证分两种,一是Client端验证,二是Server端验证

但是如果只做Client端验证,会有危险,使用者可以用一些工具跳過Client验证

但是如果只做Server端验证,每次都要把资料送回Server,如果一直验证不過,Server要处理很多次

所以最好的方法就是Client与Server都做检查,此CustomValidator就可以达到此需求了..

asp.net(c#)

CustomValidatorDoubleCheck.aspx

 

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="CustomValidatorDoubleCheck.aspx.cs" Inherits="CustomValidatorDoubleCheck" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>CustomValidatorDoubleCheck</title> </head> <body> <form id="form1" runat="server"> <div> <asp:Label ID="lblName" runat="server" Text="名稱:"></asp:Label> <asp:TextBox ID="txbName" runat="server"></asp:TextBox> <asp:Button ID="btnAdd" runat="server" Text="新增" OnClick="btnAdd_Click" /> <asp:CustomValidator ID="CustomValidator1" runat="server" ClientValidationFunction="check" ControlToValidate="txbName" Display="Dynamic" OnServerValidate="CustomValidator1_ServerValidate" ValidateEmptyText="True"></asp:CustomValidator></div> </form> </body> </html> <script type="text/javascript"> function check(source, arguments) { if(arguments.Value.length<5) { alert("長度要大於4"); arguments.IsValid = false; } else { arguments.IsValid = true; } } </script>

 

CustomValidatorDoubleCheck.aspx.cs

 

using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; public partial class CustomValidatorDoubleCheck : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args) { if (args.Value.Length < 5) { this.ClientScript.RegisterClientScriptBlock(this.GetType(), "msg", "<script>alert('長度要大於4');</script>"); args.IsValid = false; } else { args.IsValid = true; } } protected void btnAdd_Click(object sender, EventArgs e) { if (this.Page.IsValid) { Response.Write("新增成功"); } else { Response.Write("新增失敗"); } } }

 

執行結果:

转载网址:http://www.dotblogs.com.tw/puma/archive/2008/09/28/5511.aspx

转载于:https://www.cnblogs.com/zhouxiuquan/archive/2011/11/21/2299478.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值