在aspx程序使用CustomValidator验证

asp.net有一个验证控件CustomValidator,一直没有机会使用过,今天有时间做了一个测试。如果你以前写Web站点时,常使用Javascript来做客户端验证的话,这个绝对可以使用的一个验证控件。
下面Insus.NET做的例子,是让一个TextBox不能为空。在aspx写上一个TextBox 和一个Button,铵钮事件没有写什么,只是做postBack而已,另外一个就是不能少了主角 asp:CustomValidator自定义验证控件。

View Code
 <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        
<asp:CustomValidator ID="CustomValidator1" runat="server" ClientValidationFunction="ValidateTextBox"
            ErrorMessage
="文本框不能为空。"></asp:CustomValidator>
        
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />

 
 接下来,用Javascript写ClientValidationFunction的函数"ValidateTextBox" 放在aspx的head位置。

View Code
<script language="javascript" type="text/javascript">
        
function ValidateTextBox(source, args) {
            
var txtBox = document.getElementById('<%= TextBox1.ClientID %>');
            
if (txtBox.value == "")
                args.IsValid 
= false;
            
else
                args.IsValid 
= true;
        } 
    
</script>

下面结果是没有对TextBox输入任何时,点击Button的效果:

原文地址:https://www.cnblogs.com/insus/p/2058977.html