Creating a Validation Object


Since we are validating user information, the JavaScript validation object that we are going to be creating will be called UserValidator. This object will have four methods: an initialize method for initializing all the object's local variables; a setMode method, which sets the form mode from login to register; a validate method, which is the Ajax part that will make XHRs to a PHP object; and an onValidation method, which will be used as the callback method for the XHR and ultimately display the feedback to the user. When the object is created, it automatically calls the initialize method to set the local object variables. When a request is made, the validate method is called, which sets the onValidation method as a callback so that it fires when the Ajax object responds. The setMode method is set when a user clicks the Register link because this is where the mode changes from login to register.

Getting started with this object is simple. First, we need to declare it and then call its initialize method as shown in Listing 12.1.

Listing 12.1. Creating and Initializing the UserValidator Object (UserValidator.js)

UserValidator = {}; UserValidator.initialize = function(formId, modeVal, fieldNum, submitId) {     UserValidator.currentSelector = '';     UserValidator.currentForm = formId;     UserValidator.mode = modeVal;     UserValidator.fieldNumToValidate = fieldNum;     UserValidator.submitId = submitId; }

Declaring a Singleton object is nothing new, but we do have quite a few local object properties that are unique to this object and set within its initialize method. The first is a property called currentSelector, which will be used in our validate method to hold the current form field id that is being validated. The second is the currentForm property, which will be used to hold an id for the current form that is being validated. The third is the mode property, which will be used to check whether the page is in login or registration mode. The fourth is called fieldNumToValidate and will be used to hold a number that indicates how many form elements need to be validated before the Register button is enabled for a user to register. The last property is called submitId, which simply holds the id of the Submit button for the current form and will be used in the setMode method to change the value from login to register if a new user clicks the Register link. All of these properties will allow us create a form that interacts with the user. The initialize method is fired when the body in our login/registration page loads. Listing 12.2 shows how this method is added to our page.

Listing 12.2. Initializing the UserValidator Object (index.php)

<body onload="UserValidator.initialize('awadForm', 'Login', 2, 'submit');">

We are passing the values for the object properties as parameters of this method when the page loads.

The next method that we will create sets the mode for the form, switching it from login to registration in our case (see Listing 12.3). This method is called setMode and it takes one parameter, which is the new mode value. In our sample, this value will be 'Register'.

Listing 12.3. Setting the Mode from Login to Register (UserValidator.js)

UserValidator.setMode = function(modeVal) {     UserValidator.mode = modeVal;     Utilities.getElement( UserValidator.submitId ).value = modeVal;     Utilities.getElement( UserValidator.submitId ).disabled = true;     Utilities.getElement( UserValidator.currentForm ).action += "?mode="+ modeVal; }

This method takes the new mode value and sets the local mode property, which we created in the intialize method, and the value of the Submit button to this new value. It then disables the Submit button until the form is validated based on the fieldNumToValidate property that we set in the initialize method and appends the mode value to the current form's action URL. Appending this value allows us to retrieve it when the post-back happens and use it to decipher whether we need to register a new user or log in an existing one.

Validating User Input

In order to validate the two fields that we specified in the intialize method, we have to create a validate method that takes a selector parameter and its value. The selector parameter is the id for the element that is being validated and the value parameter is the value of this element. Listing 12.4 shows this completed method, which we will cover in a moment.

Listing 12.4. Validating Forms Against Database Data (UserValidator.js)

[View full width]

UserValidator.validate = function(selector, value) {     if(selector != '' && value != '')     {         UserValidator.currentSelector = selector;         var url =  "serviceConnector .php?object=UserManager&method=verifyUserInformation&params="+ selector +","+ value;         AjaxUpdater.Update("GET", url, UserValidator.onValidation);     }     else if(selector != '' && value == '')     {         Utilities.getElement( selector ).style.backgroundColor = '#ffffff';         Utilities.getElement( selector +"Message" ).innerHTML = '';     } }

Now that you have taken a look at the code, we can cover it line by line. The first thing we do is check to make sure that neither of the parameters is empty. If they are not empty, we set the currentSelector to the selector parameter and create a url variable to pass through an Ajax request. The url variable that we create consists of a serviceConnector.php file, an object parameter that is set to the userManager object that we will create soon, and a method parameter that is set to a verifyUserInformation method. The last part of the query is called param and is set to the selector and value parameters that were passed into the object. The parameters are concatenated into a comma-delimited list and the url variable is finally sent to the server through an Ajax request with the onValidation method set as the callback. Of course, there is always the possibility that the selector could be set, but the value parameter could be an empty string, so we have a condition that sets the selector element's visual feedback to the default state, just in case a user has already validated the element already.

In order to call this validation method from the client page, we need to add the code to the onblur for the form elements we want to validate. Listing 12.5 shows the body of the index.php sample page.

Listing 12.5. Calling the Validation Method from the Form (index.php)

[View full width]

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title>AJAX for Web Application Developers</title> <link href="css/user.css" rel="stylesheet" type="text/css" /> <script type="text/javascript" src="/books/1/87/1/html/2/javascript/Utilities.js"></script> <script type="text/javascript"> var jsFiles = new Array("javascript/utils/ErrorManager.js", "javascript/utils/Alert.js",  "javascript/utils/NumberUtil.js", "javascript/utils/StringUtil.js", "javascript/model /AjaxUpdater.js", "javascript/model/HTTP.js", "javascript/model/Ajax.js", "javascript/utils /UserValidator.js"); Utilities.includeJS(jsFiles); </script> </head> <body onload="UserValidator.initialize('awadForm', 'Login', 2, 'submit');"> <div >     <div style="color: #ff0000"><?=$error;?></div>     <form  method="post" action="<?= $_SERVER['PHP_SELF']; ?>">         <div  style="display: none;">             First Name: <input name="firstName"  type="text" /> <br/><br/>             Last Name: <input name="lastName"  type="text" /> <br/><br/>             E-mail: <input name="email"  type="text" onblur="javascript :UserValidator.validate(this.id, this.value);" /><div ></div><br/><br/>         </div>         <a href="#" onclick="javascript:document.getElementById('register').style.display  ='';document.getElementById('registerButton').style.display = 'none';UserValidator.setMode ('Register');" >Register<br/><br/></a>         Username: <input name="username"  type="text" onblur="javascript:if( UserValidator.mode == 'Register') UserValidator.validate(this.id, this.value);" /><div  ></div><br/><br/>         Password: <input name="password"  type="password" /> <br/><br/>         <div >             <input name='submit' type='submit' value='Login' id='submit'>         </div>     </form> </div> <div  style="display:none;"></div> </body> </html>

These validation calls are really simple and can be duplicated in any element that we want to add them to because they are getting their parameters from the current element to which they are attached. The only requirement is that there is an id attribute for the element that is calling the method. There is PHP code in the action that makes the form post back on this same page, which will require us to handle the login and registration within this page. It also has a PHP $error message that is displayed in this page if an error exists. This message will be covered in the next section when we add more PHP code to the top of this file to handle the login and registration.

Providing Visual Feedback

Visual feedback is important in web applications and often overlooked by developers. Adding visual feedback keeps users in touch with their interactions and does not leave them wondering what has happened to their data when they have clicked a button, exited a form field, and so on. Providing feedback with our UserValidator object is not difficult to accomplish because all we need to do is match element ids and change styles based on responses from our XHRs. Listing 12.6 shows this code and how it handles displaying visual clues to the user.

Listing 12.6. Providing Visual Feedback to Users (UserValidator.js)

[View full width]

<?php UserValidator.onValidation = function() {     if(Ajax.checkReadyState('loading') == "OK")     {         var color ='#ffffff';         if(Ajax.getResponse().firstChild.data == 'success')         {             color ='#ff9999';             Utilities.getElement( UserValidator.currentSelector +"Message" ).innerHTML =  'Already in use.';         }         else         {             color ='#ccff99';             Utilities.getElement( UserValidator.currentSelector  +"Message" ).innerHTML =  'OK';             UserValidator.fieldNumToValidate--;         }         Utilities.getElement( UserValidator.currentSelector ) .style.backgroundColor = color;         if(UserValidator.fieldNumToValidate == 0)         {             Utilities.getElement( UserValidator.submitId ).disabled = false;         }     } } ?>

There are quite a few conditions in this method, but don't be intimidatedthe code is very simple. The first thing we check is the ready state of the Ajax object, which we have already covered in the other components that we have created. After it verifies, we check the response to see if a success or failed message was returned from our server-side object, which we will be creating shortly. If the response is successful, it means we need to set the form element background to red and add a message stating that the data is already in use because this data already exists in the database. Otherwise, we set it to green and add an 'OK' message. We also update the fieldNumToValidate property based on the condition of the response. The last thing we check is whether the fieldNumToValidate is equal to zero and, if it is, we enable the button.

Now that we have created the client side of the request, we need to check the database and respond with the XML based on matching data.



Ajax for Web Application Developers
Ajax for Web Application Developers
ISBN: 0672329123
EAN: 2147483647
Year: 2007
Pages: 129
Authors: Kris Hadlock

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net