Client Side Validation

Here's an example that performs client-side validation using the Validator controls. Create a copy of the Web Form ch5-1.aspx. You can copy files within the Solution Explorer just as you do in the Windows Explorer. Right-click the ch5-1.aspx file in the Solution Explorer pane, then select Copy from the context menu. Next, right-click the ch5 folder, and then select Paste from the context menu. That will paste a copy of the ch5-1.aspx file named Copy of ch5-1.aspx into the ch5 folder. Rename the file ch5-2.aspx by selecting the new file and pressing F2 or right-clicking and selecting Rename from the context menu, and then typing the new name.

Copying and pasting a Web Form also pastes a copy of the code-behind file, ch5-1.aspx.cs. That can be a problem when you rename the ASPX file because, while renaming the file also renames the code-behind file, it does not rename the class created in the code-behind file. You must rename that manually. Double-click the ch5-2.aspx.cs file and rename the class ch5_2.cs (note the underscore rather than the dash).

Double-click the new Web Form to load it into the editing window. Click the Toolbox, and drag two RequiredFieldValidator controls onto the design surface. Place them just to the right of the two TextBox controls. Next, set the id property of the new controls to UsernameValidator and PasswordValidator, respectively. Set other properties for the controls as follows:

Double-click the new Web Form to load it into the editing window. Click the Toolbox, and drag two RequiredFieldValidator controls onto the design surface. Place them just to the right of the two TextBox controls. Next, set the id property of the new controls to UsernameValidator and PasswordValidator, respectively. Set other properties for the controls as follows:

Property

UsernameValidator

PasswordValidator

ControlToValidate

txtUserName

txtPassword

ErrorMessage

Username required

Password Required

When you finish, the Web Form should look like Figure 5.3.

Use£ Niirre:

'Jir^ipie rccTJTi'i

Password;

TiUftw-d Rigjzid

cut

Figure 5.3: Simple login page with RequiredFieldValidator s

Figure 5.3: Simple login page with RequiredFieldValidator s

Run the Web Form again. This time, submit the form without entering text into either the User Name or Password field. The submission triggers the validation check. The validation check fails for both controls, because the RequiredFieldValidator control performs only one check—it tests whether the control referred to by its ControlToValidate property contains a value different from the control's initial value. Stop the program and run it again. Enter some text into one of the two fields but not the other. You should see the error message appear for the empty field only.

Validators are "smart" controls. They follow the rule mentioned in the beginning of this section and perform the validation as closely as possible to the point of input. In this case, that point is heavily dependent on the browser. Using IE5 or higher, the controls generate client-side JavaScript or VBScript (depending on the setting of the defaultClientScript Page property). Using downlevel browsers, the controls generate no client script, and validation fires on the server when the user submits the form.

How does this all work? It's worth exploring a bit so that you'll understand the model. Using IE5, for example, with the defaultClientScript property set to JavaScript, the page generates the script in Listing 5.3. You can see the full HTML generated by the page yourself by running the program and then selecting View Source from the browser context menu. The highlighted sections show how ASP.NET translates the validation controls into HTML.

Listing 5.3: HTML Code as Sent to the Browser for the Login Form with

RequiredFieldValidator (ch5-2.aspx)

<META http-equiv="Content-Type"

content="text/html; charset=windows-1252"> <meta content="http://schemas.microsoft.com/intellisense/ie5" name="vs targetSchema"> <meta content="Microsoft Visual Studio.NET 7.0" name="GENERATOR"> <meta content="C#" name="CODE_LANGUAGE"> </HEAD>

<body ms positioning="GridLayout">

form name="FORM1" method="post" action="ch5-2.aspx"

language="javascript" onsubmit="ValidatorOnSubmit();" id="FORM1">

<input type="hidden" name="_VIEWSTATE"

value="dDwtMTYzMDIzNDQwMjs7Pg==" />

<script language="javascript"

src="/aspnet_client/system_web/1_4 0 0 0_2 914_16/WebUIValidation.js"> </script>

<table style="Z-INDEX: 101; LEFT: 122px; POSITION: absolute; TOP: 10 6px"

height="137" cellSpacing="1" cellPadding="1" width="474" bgColor="#ffffcc" border="1"> <tr>

<span id="Label1" style="background-color:#FFFFC0;border-color:Transparent;border-style:None;font-family:Verdana; font-size:Small;font-weight:bold;height:18px; width:135px;">User Name:</span> <input name="txtUserName" type="text" id="txtUserName" /> <span id="UsernameValidator" controltovalidate="txtUserName" errormessage="Username required"

evaluationfunction="RequiredFieldValidatorEvaluateIsValid"

initialvalue="" style="color:Red;visibility:hidden;">Username required</span>

<span id="Label2" style="background-color:#FFFFC0;

border-color:Transparent;border-style:None;font-family:Verdana; font-size:Small;font-weight:bold;height:18px;width:13 6px;"> Password:</span> <input name="txtPassword" type="password" id="txtPassword" /> <span id="PasswordValidator" controltovalidate="txtPassword" errormessage="Password Required"

evaluationfunction="RequiredFieldValidatorEvaluateIsValid" initialvalue="" style="color:Red;visibility:hidden;">Password Required</span>

<td align="middle" width="200">

<input type="submit" name="cmdCancel" value="Cancel"

onclick="if (typeof(Page_ClientValidate) == 'function') Page ClientValidate(); " language="javascript" id="cmdCancel" style="font-family:Verdana;font-weight:bold;height:2 4px; width:104px;" /> </td>

<td align="middle" width="200">

<input type="submit" name="cmdOK" value="OK"

onclick="if (typeof(Page ClientValidate) == 'function') Page ClientValidate(); " language="javascript" id="cmdOK" style="font-family:Verdana;font-weight:bold;height:2 5px; width:101px;" /> </td> </tr> </table>

<script language="javascript"> <!--

var Page Validators = new Array(document.all["UsernameValidator"], document.all["PasswordValidator"]); // -- >

<script language="javascript"> <!--

var Page ValidationActive = false; if (typeof(clientInformation) != "undefined" &&

clientInformation.appName.indexOf("Explorer") != -1) { if (typeof(Page ValidationVer) == "undefined") alert("Unable to find script library " + "'/aspnet client/system web/" + "1_4000_2914_16/WebUIValidation.js'." +

"Try placing this file manually, or reinstall by running " + "'aspnet regiis -c'."); else if (Page_ValidationVer != "121")

alert("This page uses an incorrect version of " + "WebUIValidation.js. The page expects version 121. " + "The script library is " + Page_ValidationVer + "."); else

ValidatorOnLoad();

function ValidatorOnSubmit() {

if (Page ValidationActive) {

ValidatorCommonOnSubmit();

The interesting and functional part here is the client-side script. First, note that the page includes a script file:

<script language="javascript"

src="/aspnet_client/system_web/1_4 0 0 0_2 914_16/WebUIValidation.js"> </script>

That script file contains several utility functions for validating input. You should be able to find the file by following the path from your root Web directory. On my computer, the full path is as follows:

<script language="javascript"

src="/aspnet_client/system_web/1_4 0 0 0_2 914_16/WebUIValidation.js"> </script>

The path may vary on your computer, because it's version dependent, but you should be able to match the value of the script's src attribute to a physical path on your server. Farther down in the file, you'll see a script that defines several variables and then checks whether the script was found and loaded by checking the Page_ValidationVer variable defined in the included script. The page displays message boxes (using the alert function in JScript) if either condition fails.

if (typeof(clientInformation) != "undefined" &&

clientInformation.appName.indexOf("Explorer") != -1) { if (typeof(Page ValidationVer) == "undefined") alert("Unable to find script library " + "'/aspnet_client/system_web/1_4000_2914_16/" + "WebUIValidation.js'. " + "Try placing this file manually, " + "or reinstall by running 'aspnet regiis -c'."); else if (Page_ValidationVer != "121")

alert("This page uses an incorrect version of " + "WebUIValidation.js. The page expects version 121. " + "The script library is " + Page_ValidationVer + "."); else

ValidatorOnLoad();

The real work occurs when the user clicks a button. Each operation that submits the form calls a function to check the data entered into the form. For example, here's the OK button definition. The onClick event checks to see whether a function called Page_ClientValidate exists; if so, it calls the function.

<input type="submit" name="cmdOK" value="OK"

onclick="if (typeof(Page ClientValidate) == 'function') Page ClientValidate(); " language="javascript" id="cmdOK" style="font-family:Verdana;font-weight:bold;height:2 5px; width:101px;" /> </td>

The Page_ClientValidate function iterates through the Validator controls in the document, calling the ValidatorValidate function for each one.

function Page ClientValidate() { var i;

ValidatorValidate(Page Validators[i]);

ValidatorUpdateisValid(); ValidationSummaryOnSubmit(); Page BlockSubmit = !Page isValid; return Page isValid;

The ValidatorValidate function fires the evaluation function bound to each validator, which in turn performs the appropriate test on the value of the control to which the validator is bound through its

ControlToValidate property.

function ValidatorValidate(val) { val.isvalid = true; if (val.enabled != false) {

if (typeof(val.evaluationfunction) == "function") { val.isvalid = val.evaluationfunction(val);

ValidatorUpdateDisplay(val);

After iterating through all the validators, the Page_ClientValidate function calls a Validator-UpdateisValid() function, which iterates through the page validators again, checking the isvalid property for each. If any of the isvalid properties returns false, the script sets a page-level variable called Page_isValid to false and exits the loop.

So far, nothing's prevented the form from submitting, though. The <form> tag's onsubmit property calls another function called ValidatorOnSubmit(). That script checks to see if the validators are loaded and working properly by checking the value of a variable named Page_Validationactive that is set to true only when the ValidatorOnLoad() function executes properly. Finally, it calls the

ValidatorCommonOnSubmit() function.

function ValidatorOnSubmit() {

if (Page ValidationActive) {

ValidatorCommonOnSubmit();

The common validation routine ValidatorCommonOnSubmit sets the event object's returnValue property to the inverse value of the Page_BlockSubmit variable that was set in the Page_Client-Validate() function. That's a little difficult to read, but if you translate it to English, it sounds better. "If the page should block submission, then return false, otherwise return true." If the event.returnValue is true, the form will submit the data to the server; otherwise, it won't do anything.

function ValidatorCommonOnSubmit() {

event.returnValue = !Page BlockSubmit; Page BlockSubmit = false;

Finally, the function sets the Page_BlockSubmit variable to false to get ready for the next validation round (in other words, it clears the variable so the form will submit the next time if the user fixes the invalid input values). While all this client script is anything but simple, you usually won't need to think about it at all.

Note There have been several versions of the client-side validation script file. I've used version 121 in this example. Your version may be different, but the differences should be slight.

Now that you've seen a simple validation control, you can extend the validation a little. As I stated earlier, in addition to checking that the user has entered a value, you will want to perform a couple of other checks. The next example enforces a complex rule that usernames may contain only letters and numbers, that they must be between 3 and 10 characters long, and that passwords may contain any characters but must be between 6 and 10 characters long. You can perform these types of tests with a RegularExpressionValidator control. Make a copy of the ch5-2.aspx Web Form and rename it ch5-3.aspx (see the procedure listed earlier in this chapter to copy a Web Form). Drag two

RegularExpressionValidator controls onto the Web Form. Place them under the table. Make them as wide as the table and two or three lines high. Set the id property of the new controls to

UsernameRegExpValidator and PasswordRegExpValidator. Set other properties for the controls as follows:

RegularExpressionValidator controls onto the Web Form. Place them under the table. Make them as wide as the table and two or three lines high. Set the id property of the new controls to

UsernameRegExpValidator and PasswordRegExpValidator. Set other properties for the controls as follows:

Property

UsernameRegExpValidator

PasswordRegExpValidator

ControlToValidate

txtUserName

txtPassword

ErrorMessage

Invalid Username:

Usernames must be between 3 and 10

characters, and may contain

only letters and numbers.

Invalid Password

ValidationExpression

[a-zA-Z 0-9]{3,10}

.{6,10}

Display

Dynamic (or Static)

Dynamic (or Static)

EnableClientScript

True

True

The ValidationExpression property contains the regular expression that the validator uses to test the value of the control specified by the ControlToValidate property. The expression [a-zA-Z_0-9]{3, 10} accepts alphanumeric characters and the underscore and limits the matched value to between 3 and 10 characters in length, inclusive. When you run the program, the same actions occur as before; the page generates client-side JavaScript to validate the control, and the validator checks the entered values using the regular expression. Try it. Enter two characters into the User Name field and then press the Tab key. The validation fires immediately. Your browser should look similar to Figure 5.4.

fcl ■'■«■■ J ■ NUIJ. I L1I.H..U || ¡III ^m r-i '.-- ItMil* r-Ji rbL- - - J 1 * '-■-■ . .t . ,■ t ■

UserNnrw;

I'j^vjord: ;

PK

Ii.-ji-.'!—I1 T. irv : hr "r.-.jm i ti-t 1 rkaj hi I jti: rjr. ■ai'*.' ii\ ^J u '

Ii.-ji-.'!—I1 T. irv : hr "r.-.jm i ti-t 1 rkaj hi I jti: rjr. ■ai'*.' ii\ ^J u '

Figure 5.4: Regular-Expression-Validator control example

Was this article helpful?

0 0

Post a comment