Validating using AJAX Validating example structure Filed validating Form validating
Validating structure- flow chart
AJAX Validation AJAX-style—when each form field loses focus (onblur). The field's value is sent to the server, which validates the data and returns a result (0 for failure, 1 for success). If validation fails, an error message will unobtrusively show up and notify the user about the failed validation PHP-style—when the entire form is submitted. This is the usual validation you would do on the server, by checking user input against certain rules. If no errors are found and the input data is valid, the browser is redirected to a success page as shown in Figure 4.4. If validation fails, however, the user is sent back to the form page with the invalid fields highlighted
Validation rules Username must not already exist in the database Name field cannot be empty A gender must be selected Month of Birth must be selected Birthday must be a valid date (between 1-31) Year of birth must be a valid year (between ) The date must exist taking into consideration the number of days for each month address must be written in a valid format, such as or Phone number must be written in standard US form: xxx- xxx-xxxx "I've read the Terms of Use" must be checked
Validating forms example Things happen after submitting Index.php structure: require_once ('index_top.php');
Validate.js // holds an instance of XMLHttpRequest var xmlHttp = createXmlHttpRequestObject(); // holds the remote server address var serverAddress = "validate.php"; // when set to true, display detailed error messages var showErrors = true; // initialize the validation requests cache var cache = new Array(); function createXmlHttpRequestObject() // the function handles the validation for any form field function validate(inputValue, fieldID) // function that handles the HTTP response function handleRequestStateChange() { readResponse(); } // read server's response function readResponse() function setFocus() { document.getElementById("txtUsername ").focus(); }
Validate JavaScript function function validate(inputValue, fieldID) { // only continue if xmlHttp isn't void if (xmlHttp) { // if we received non-null parameters, we add them to cache in the // form of the query string to be sent to the server for validation if (fieldID) { // encode values for safely adding them to an HTTP request query string inputValue = encodeURIComponent(inputValue); fieldID = encodeURIComponent(fieldID); // add the values to the queue cache.push("inputValue=" + inputValue + "&fieldID=" + fieldID); } // try to connect to the server try { // continue only if the XMLHttpRequest object isn't busy // and the cache is not empty if ((xmlHttp.readyState == 4 || xmlHttp.readyState == 0) && cache.length > 0) { // get a new set of parameters from the cache var cacheEntry = cache.shift(); // make a server request to validate the extracted data xmlHttp.open("POST", serverAddress, true); xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); xmlHttp.onreadystatechange = handleRequestStateChange; xmlHttp.send(cacheEntry); } catch (e) { // display an error when failing to connect to the server displayError(e.toString()); }
readReponse function function readResponse() { // retrieve the server's response var response = xmlHttp.responseText; // server error? if (response.indexOf("ERRNO") >= 0 || response.indexOf("error:") >= 0 || response.length == 0) throw(response.length == 0 ? "Server error." : response); // get response in XML format (assume the response is valid XML) responseXml = xmlHttp.responseXML; // get the document element xmlDoc = responseXml.documentElement; result = xmlDoc.getElementsByTagName("r esult")[0].firstChild.data; fieldID = xmlDoc.getElementsByTagName("fi eldid")[0].firstChild.data; // find the HTML element that displays the error message = document.getElementById(fieldID + "Failed"); // show the error or hide the error message.className = (result == "0") ? "error" : "hidden"; // call validate() again, in case there are values left in the cache setTimeout("validate();", 500); }
Validate.php structures <?php // start PHP session session_start(); // load error handling script and validation class require_once ('error_handler.php'); require_once ('validate.class.php'); // Create new validator object $validator = new Validate(); // read validation type (PHP or AJAX?) $validationType = ''; if (isset($_GET['validationType'])) { $validationType = $_GET['validationType']; } // AJAX validation or PHP validation? if ($validationType == 'php') { // PHP validation is performed by the ValidatePHP method, which returns // the page the visitor should be redirected to (which is allok.php if // all the data is valid, or back to index.php if not) header("Location:". $validator->ValidatePHP()); } Else { ajax checking: next week;} ?>
Validate.class.php structures The file declare the classed which used by validate.php: –Open database –Public function ValidateAJAX –Public function ValidatePHP If no errors are found, point to a successful validation page allok.php Otherwise return to index.php –Private functions about the field validation.
Private Functions of validate.class.php (1) // validate user name (must be empty, and must not be already registered) private function validateUserName($value) { // trim and escape input value $value = $this->mMysqli->real_escape_string(trim($value)); // empty user name is not valid if ($value == null) return 0; // not valid // check if the username exists in the database $query = $this->mMysqli->query('SELECT user_name FROM users '. 'WHERE user_name="'. $value. '"'); if ($this->mMysqli->affected_rows > 0) return '0'; // not valid else return '1'; // valid }
Private Functions of validate.class.php (2) // validate name private function validateName($value) { // trim and escape input value $value = trim($value); // empty user name is not valid if ($value) return 1; // valid else return 0; // not valid }
Private Functions of validate.class.php (3) // validate gender private function validateGender($value) { // user must have a gender return ($value == '0') ? 0 : 1; } // validate birth month private function validateBirthMonth($value) { // month must be non-null, and between 1 and 12 return ($value == '' || $value > 12 || $value < 1) ? 0 : 1; } // validate birth day private function validateBirthDay($value) { // day must be non-null, and between 1 and 31 return ($value == '' || $value > 31 || $value < 1) ? 0 : 1; }
Private Functions of validate.class.php (4) // validate birth year and the whole date private function validateBirthYear($value) { // valid birth year is between 1900 and 2000 // get whole date (mm#dd#yyyy) $date = explode('#', $value); // date can't be valid if there is no day, month, or year if (!$date[0]) return 0; if (!$date[1] || !is_numeric($date[1])) return 0; if (!$date[2] || !is_numeric($date[2])) return 0; // check the date return (checkdate($date[0], $date[1], $date[2])) ? 1 : 0; }
Private Functions of validate.class.php (5) // validate private function validate ($value) { // valid formats: return ]+)*(\.[a-z]{2,3})$', $value)) ? 0 : 1; } // validate phone private function validatePhone($value) { // valid phone format: ###-###-#### return (!eregi('^[0-9]{3}-*[0-9]{3}-*[0-9]{4}$', $value)) ? 0 : 1; }
Private Functions of validate.class.php (6) // check the user has read the terms of use private function validateReadTerms($value) { // valid value is 'true' return ($value == 'true' || $value == 'on') ? 1 : 0; }