轉帖|其它|編輯:郝浩|2011-02-09 15:40:20.000|閱讀 514 次
概述:CustomValidator控件允許用戶自定義驗證,可以在服務器端驗證,可以在客戶端驗證,也可以在客戶端和服務端同時驗證,本文主要介紹CustomValidator驗證控件使用,希望對大家有幫助。
# 界面/圖表報表/文檔/IDE等千款熱門軟控件火熱銷售中 >>
CustomValidator控件允許用戶自定義驗證,可以在服務器端驗證,可以在客戶端驗證,也可以在客戶端和服務端同時驗證
下面的例子是驗證一個數能否被2整除
1.服務器端驗證
在驗證的時候會用到IsValid這個屬性,根據IsValid的值(true/false)來判斷是否通過頁面驗證。
a. 拖放控件TextBox用于輸入值;Button用于測試驗證狀態,IsValid為true觸發Click事件;CustomValidator控制要驗證的對象和驗證事件等。
b. 設置CustomValidator的屬性這里設置ErrorMessage為Not an even number!,ControlToValidate為Text1
c. 編寫CustomValidator的ServerValidation事件
protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
{
try
{
int num = int.Parse(args.Value);
args.IsValid = ((num%2)==0);
}
catch (Exception ex)
{
args.IsValid = false;
}
}
d. 編寫Button的Click事件
protected void Button2_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
Response.Redirect("gouWuChe.aspx");
}
else
{
//提示
}
}
2. 客戶端驗證
使用javascript function驗證,并用設置ClientValidationFunction為javascript 驗證函數(function)
a. Javascript 函數
<script language="javascript">
function ValidateNumber(source,args)
{
if(args.Value%2==0)
{
args.IsValid=true;
}
else
{
args.IsValid=false;
}
}
</script>
b. 設置CustomValidator的屬性這里設置ErrorMessage為請輸入能被2整除的數,ControlToValidate為TextBox1, ClientValidationFunction為ValidateNumber
c. 編寫Button的Click事件
protected void Button2_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
Response.Redirect("gouWuChe.aspx");
}
else
{
//提示
}
}
3. 客戶端和服務端同時驗證
將上面的兩部分代碼合并可以了
本站文章除注明轉載外,均為本站原創或翻譯。歡迎任何形式的轉載,但請務必注明出處、不得修改原文相關鏈接,如果存在內容上的異議請郵件反饋至chenjj@fc6vip.cn
文章轉載自:網絡轉載