Web Studyaspnet.blogspot.com Babyneed.blogspot.com

ASP.Net Web Developer Guide

Power By: eXTReMe Tracker Powered by Blogger  
 
 
 
 

 

 
Important Links
 
   
     
 
Sitemap
 
   
   
 
Reference
 
   

Sunday, March 26, 2006

The CustomValidator Control (Chapter 3)

In many situations, we may not be able to use the existing validators to validate a complex rule. In that case, we may apply a CustomValidator. When applying a CustomValidator, we may provide our own functions that will return true or false. We may develop the code for server-side validation only, or we may develop the code for server-side as well as the client-side validation. Suppose that the user will enter the data about his or her department number. Also suppose that the department number must be evenly divisible by 10.We will develop a simple custom validator to enforce this rule at the server-side.The run-time display of this application is shown in Figure 3.56.
Figure 3.56 Using the CustomValidator Control

We have developed a VB function named validateDeptNum to perform the check.We have also specified its name in the onServerValidate property of the CustomValidator control.
Figure 3.57 The Code for CustomValidator (Validator5.aspx)
What is your Department Number?
<asp:TextBox id="txtDeptNum" width ="40" runat="server" />
<asp:CustomValidator id="cusvDeptNum" runat="server"
display="static" controlToValidate="txtDeptNum"
onServerValidate="validateDeptNum"
errorMessage="Must be in multiples of 10" >
</asp:CustomValidator></br>
<asp:Button id="btnSubmit" runat="server" text="Submit" />
</form></body></html>
<script language="VB" runat="server">
Sub validateDeptNum(source As Object, s as ServerValidateEventArgs)
If (CInt(s.Value) Mod 10)=0 Then
s.IsValid= True
Else
s.IsValid=False
End If
End Sub
</script>
Although this example illustrates the server-side validation,ASP.NET automaticallywrites client-side code to perform the validation.There are various options available to prevent this from occurring and also not to display the code that shows the client-side JavaScript validation.We will not be going into these in detail. In the server-side custom validation, the validation function is included in the server-side script tag <script language=“VB” runat=“server”>. We need to specify the name of the validation function in the OnServerValidate property of the CustomValidator control.The validator control calls this function with two parameters: the first parameter is the control itself, whereas the second parameter is an instance of the ServerValidateEventArgs class.This object encapsulates the methods and properties that enable us to access the value of the control being validated and to return whether the control has been validated or not.

0 Comments:

Post a Comment

<< Home