Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

ASP .NET Web Developer s Guide - Mesbah Ahmed, Chris Garrett

.pdf
Скачиваний:
37
Добавлен:
24.05.2014
Размер:
7.32 Mб
Скачать

120 Chapter 3 • ASP Server Controls

Figure 3.57 Continued

s.IsValid=False

End If

End Sub

</script>

Although this example illustrates the server-side validation, ASP.NET automatically writes 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.

NOTE

If the client-side validation is active (which is the default), the browser does not submit the form back to the server until all corrections have been made on the client-side. If you have a “server-side-only” custom validator along with some other fields that employ client-side validation, then on click of the submit button, the form may not appear to work properly. That is expected because the browser will not submit the form until all client-side validated fields are correct.

CustomValidator with Explicit

Client-Side Validation Function

In the CustomValidator, we may specify a twin client-side validation function. To employ the client-side validation, we will have to specify the name of the client-side validation function in the ClientValidationFunction property of the

CustomValidator control.The client-side function needs to be coded in JavaScript,

www.syngress.com

ASP Server Controls • Chapter 3

121

and it should also return true or false. Obviously, the client-side validation should perform the same checks that are done by the server-side validation function.

We will revise our previous example to include a client-side validation function.We have already developed the server-side validation function for the department number textbox. Now we will implement the client-side validation. The run-time display of the application is shown in Figure 3.58.

Figure 3.58 Using CustomValidator with Explicit Client-Side Validation

The part of the code that is pertinent to our example is shown in Figure 3.59. In this code, you will notice that we have specified the name of the JavaScript validation function in the ClientValidationFunction property of the control to be validated.The complete code is available in Validator6.aspx in the CD.

Figure 3.59 Partial Listing of Validator6.aspx

<asp:CustomValidator id="cusvDeptNum" runat="server"

display="dynamic" controlToValidate="txtDeptNum"

onServerValidate="validateDeptNum"

ClientValidationFunction="checkModTen"

errorMessage="Dept. Number must be a multiple of 10" > </asp:CustomValidator></br>

<script language="javascript" > function checkModTen(source, s)

{var y=parseInt(s.Value);

if ((y % 10) == 0 && !(isNaN(y))) s.IsValid=true;

else s.IsValid=false;

Continued

www.syngress.com

122 Chapter 3 • ASP Server Controls

Figure 3.59 Continued

}

</script>

Displaying the Error Message with Style

In this example, we will set various properties of the validation controls to display its message with style.The output of the application is shown in Figure 3.60.We have set a number of properties, such as forecolor, bordercolor, tooltip, and so on, to our number of dependent validators.

Figure 3.60 Displaying Error Message with Style

The part of the code that is relevant to format the validator is shown in Figure 3.61.The complete code is available in the file named Validator7.aspx on the CD.

Figure 3.61 Validator7.aspx

<asp:RangeValidator id="ranvDependents" runat="server"

backcolor="salmon" forecolor="blue" bordercolor="green" borderstyle=Solid borderwidth=5 font-bold=True font-italic=True font-size="14" height="20"

tooltip="Cannot have more than 20 dependents."

text="Bad Number. Must be less than 21"

width="250" display="dynamic" controlToValidate="txtDependents"

errorMessage="Number of dependents must be from 0 to 20"

type="Integer" minimumValue=0 maximumValue=10>

</asp:RangeValidator></br>

www.syngress.com

ASP Server Controls • Chapter 3

123

The ValidationSummary Control

The ValidationSummary control enables us to display all errors in a given location. It displays the “errorMessage” properties of respective controls in the summary report. Since the error messages are displayed in the summary, often we suppress the detailed error message in the individual ValidatorControls by placing an asterisk (*) or a short message right after the validator control’s start-tag. Major properties of the ValidationSummary control are the following:

headerText This is simply a header.

displayMode Displays the errors in one of the following ways:

List

BulletList (default)

Singleparagraph

ShowSummary: (True or False) This property can be used to display or hide the summary report programmatically.

Figure 3.62 illustrates the use of a ValidationSummary control. In our example, we have defined the ValidationSummary control as follows.

<asp:ValidationSummary id="valSummary" runat="server"

headerText="Please correct the following errors"

display="static" showSummary= "True" />

Figure 3.62 Using the ValidationSummary Control

www.syngress.com

124 Chapter 3 • ASP Server Controls

The complete code for the application is shown in Figure 3.63 and is available in the file named Validator8.aspx on the CD.

Figure 3.63 The Complete Code for the Application (Validator8.aspx)

<!—- Chapter3\Validator8.aspx —>

<%@ Page Language="VB" Debug="true" %> <html><head</head>

<title>Example on ValidationSummary control </title> <body><form runat="server">

Enter Your Name:

<asp:TextBox id="txtName" rows="1" width="100" runat="server"/> <asp:RequiredFieldValidator id="validTxtName" runat="server"

controlToValidate="txtName" errorMessage="Name must be entered" display="static">*

</asp:RequiredFieldValidator></br> Hours worked?

<asp:TextBox id="txtH" width ="60" runat="server" /> <asp:RequiredFieldValidator id="validTxtH" runat="server"

controlToValidate="txtH" errorMessage="Hours must be entered" display="static">*

</asp:RequiredFieldValidator> <asp:RegularExpressionValidator id="regvH" runat="server"

display="static" controlToValidate="txtH" errorMessage="Hours must be 1-3 digits only" validationExpression="\d{1,3}">*

</asp:RegularExpressionValidator></br> Hourly Rate?

<asp:TextBox id="txtR" width ="60" runat="server" /> <asp:CompareValidator id="comvR" runat="server" display="static"

controlToValidate="txtR" errorMessage="Rate must be numeric" type="Double" operator="DataTypeCheck">*

</asp:CompareValidator></br> Number of Dependents:

<asp:TextBox id="txtDependents" width ="60" runat="server" /> <asp:RangeValidator id="ranvDependents" runat="server"

Continued

www.syngress.com

ASP Server Controls • Chapter 3

125

Figure 3.63 Continued

backcolor="salmon" forecolor="blue" bordercolor="green" borderstyle="Solid" borderwidth="5" font-bold="True" font-italic="True" font-size="14" height="20" tooltip="Cannot have more than 20 dependents." text="Bad Number. Must be less than 21" width="250" display="dynamic" controlToValidate="txtDependents"

errorMessage= "Number of dependents must be from 0 to 20" type="Integer" minimumValue="0" maximumValue="10">*

</asp:RangeValidator><br>

What is your Department Number?

<asp:TextBox id="txtDeptNum" width ="60" runat="server" /> <asp:CustomValidator id="cusvDeptNum" runat="server"

display="dynamic" controlToValidate="txtDeptNum" onServerValidate="validateDeptNum" ClientValidationFunction="checkModTen"

errorMessage= "Dept. Number must be a multiple of 10" >* </asp:CustomValidator><br>

<asp:Button id="btnSubmit" runat="server" text="Submit"/><br><br> <asp:ValidationSummary id="valSummary" runat="server"

headerText="Please correct the following errors" display="static" showSummary= "True" /><br>

</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>

<script language="javascript"> function checkModTen(source, s)

Continued

www.syngress.com

126 Chapter 3 • ASP Server Controls

Figure 3.63 Continued

{var y=parseInt(s.Value);

if (isNaN(y) && !((y % 10) == 0))

s.IsValid=false;

else

s.IsValid=true;

}

</script>

Validating Patterned Strings, Passwords, and Dates

Suppose that we want the user to enter the phone number, date of birth, hiredate, password, and confirmation of password. Also suppose that the business environment dictates that we enforce the following constraints:

The phone number must follow a pattern like (ddd)ddd-dddd for employees in the USA. It should match dd.dd.dd.dd for employees in France.

The date of birth must be between 1/1/1940 and 1/12/1985.

Hire date must be after the date of birth and before 6/15/2001.

The user should enter the password twice, and both entries must be identical.

We have developed an application to enforce these business rules.The output of the application is shown in Figure 3.64.

Figure 3.64 Validating Patterned Strings and Passwords

www.syngress.com

ASP Server Controls • Chapter 3

127

The complete code for this application is shown in Figure 3.65 and is available on the CD in the file named Validator9.aspx.We have enforced the underlying constraints as follows:

Constraint 1. We will use a regular expression to implement this constraint.The following regular expressions are identical. Both of these expressions will test the pattern (ddd)ddd-ddd:

ValidationExpression="\(\d\d\d\)\d\d\d\-\d\d\d\d">

ValidationExpression="\(\d{3}\)\d{3}\-\d{4}"

However, for French employees we must also test a pattern like dd.dd.dd.dd.The regular expression for this pattern would be this:

ValidationExpression="\d{2}\.\d{2}\.\d{2}\.\d{2}"

We may parenthesize these two expressions and connect them with a pipe ( | ) symbol to specify that any one of the expressions needs to be satisfied, as follows:

ValidationExpression="(\(\d{3}\)\d{3}\\d{4})|

(\d{2}\.\d{2}\.\d{2}\.\d{2})"

Constraint 2. We have used a RangeValidator to enforce this rule.

Constraint 3. We have used a combination of the CompareValidator and the RangeValidator.The CompareValidator checks whether the date in txtDateHired is greater than that in txtDateOfBirth.The code for that is as follows:

Hire Date?

<asp:TextBox id="txtDateHired" rows="1" width="100" runat="server"/> <asp:CompareValidator id="compDateHired" runat="server"

display="dynamic"

controlToValidate="txtDateHired"

controlToCompare="txtDateOfBirth"

errorMessage="Hire Date must be after Date of Birth" type="String" operator="GreaterThan">

</asp:CompareValidator><br/>

The RangeValidator checks whether the date in txtDateHired is less than “6/15/2001.”The minimumValue is set to “1/1/1900” because the

www.syngress.com

128 Chapter 3 • ASP Server Controls

RangeValidator will not work unless both the minimumValue and maximumValue are both present.The code snippet follows:

<asp:RangeValidator id="ranvDateHired" runat="server" type="Date"

display="dynamic" controlToValidate="txtDateHired"

errorMessage="Hire date must be before 6/1/2001"

minimumValue="1/1/1900" maximumValue="6/15/2001" >

</asp:RangeValidator><br/>

Constraint 4. Two asp:TextBox controls have been used.The TextMode properties have been set to “Password”. CompareValidator has been attached to the txtConfirmPassword. Its ControlToCompare property has been set to “txtPassword.”:

controlToValidate="txtConfirmPassword" controlToCompare="txtPassword"

type="String" operator="Equal"

Figure 3.65 Validator9.aspx

<!—- Chapter3\Validator9.aspx —> <html><head</head><body><form runat="server"> Phone Number? (ddd)ddd-dddd or dd.dd.dd.dd  

<asp:TextBox id="txtPhone" rows="1 " width="100" runat="server"/> <asp:RequiredFieldValidator id="validTxtName" runat="server"

controlToValidate="txtPhone" errorMessage="Name must be entered" display="dynamic">

</asp:RequiredFieldValidator>

<asp:RegularExpressionValidator id="regvPhone" runat="server" display="dynamic" controlToValidate="txtPhone" errorMessage="Incorrect Phone Number" validationExpression=

"(\(\d{3}\)\d{3}\-\d{4})|(\d{2}\.\d{2}\.\d{2}\.\d{2})"> </asp:RegularExpressionValidator><br>

Date of Birth? (mm/dd/yyyy) :

<asp:TextBox id="txtDateOfBirth" rows="1" width="100" runat="server"/> <asp:RangeValidator id="ranvDob" runat="server" type="Date"

display="dynamic" controlToValidate="txtDateOfBirth"

Continued

www.syngress.com

ASP Server Controls • Chapter 3

129

Figure 3.65 Continued

errorMessage= "Must be within 1/1/1940 and 12/1/1985" minimumValue="1/1/1940" maximumValue="12/1/1985">

</asp:RangeValidator></br> Hire Date?

<asp:TextBox id="txtDateHired" rows="1 " width="100" runat="server"/> <asp:CompareValidator id="compDateHired" runat="server"

display="dynamic" controlToValidate="txtDateHired" controlToCompare="txtDateOfBirth"

errorMessage="Hire Date must be after Date of Birth" type="String" operator="GreaterThan">

</asp:CompareValidator><br/>

<asp:RangeValidator id="ranvDateHired" runat="server" type="Date" display="dynamic" controlToValidate="txtDateHired" errorMessage="Hire date must be before 6/1/2001" minimumValue="1/1/1900" maximumValue="6/15/2001" >

</asp:RangeValidator><br/>

Password?

<asp:TextBox id="txtPassword" textmode="password" width="100" runat="server"/><br/>

Confirm Password:

<asp:TextBox id="txtConfirmPassword" textMode="password" width="100" runat="server" />

<asp:CompareValidator id="comvConfirmPassword" runat="server" display="static" controlToValidate="txtConfirmPassword" controlToCompare="txtPassword"

errorMessage="Both passwords must be same" type="String" operator="Equal">

</asp:CompareValidator><br/>

<asp:Button id="btnSubmit" runat="server" text="Submit"/> <br><br><br>

www.syngress.com