This tutorial shows how to Check and Validate input form field when loses focus (onblur event), with PHP via Ajax.
This script is useful when you want to check form field values with data stored on server, without refreshing the page.

    - To Download the script with the example presented in this tutorial, click: Validate input field with PHP via Ajax.

- Demo:
Valid data for this form: (Name = coursesweb; Password = mypass; E-mail = me@domain.com).
- When ALL the input fields are validated, the submit button is enabled and the form is Automatically submited.




• First, we create the HTML form. Each input field must be added into a <label>, <span>, or <div> element, together with a <span> tag with class="err", in this item it is added the error message associated to that input field.
- Example with a form with 3 input text fields, for Name, Password and E-mail:
<form action="some_script.php" method="post">
 <label for="exname">Name: <input type="text" id="exname" name="exname" /><span class="err"></span></label>
 <div>Password: <input type="password" id="expass" name="expass" /><span class="err"></span></div>
 <label for="exmail">E-mail: <input type="text" id="exmail" name="exmail" /><span class="err"></span></label><br/>
 <input type="submit" id="exsbm" disabled="disabled" value="Send" />
</form>
The idea is that both the input field and the item with class="err" must be added into a parent element, usually <label>, but can also be a <div> (like the password field from this example).

• Then we use the following JavaScript object with an Ajax function that is called when the input field is changed (detected when it loses focus, or on enter). The Ajax function sends the name and the value to a PHP script that checks and validates the received value.
If the response from the PHP script is not an empty string, the field is not valid, and the JavaScript object changes the CSS class of the input field, and adds the PHP response in the item with: class="err" associated to that field.
The field is valided when the PHP response is an empty string.

- To use this script, create an object instance of checkFormElm(), passing the ID of the submit button, and an array with the IDs of the input fields, like in this example:
/* HERE ADD THE checkFormElm() function */
// array with IDs of the fields to validate
var fields = ['exname', 'expass', 'exmail'];

// create an object instance of checkFormElm(), passing the ID of the submit button, and the $fields
var chkF = new checkFormElm('exsbm' fields);

JavaScript script with the Ajax function to check and validate form field

<script>
// object to validate form fields when they lose focus, via Ajax
// receives the ID of the Submit button, and an Array with the IDs of the fields which to validate
var checkFormElm = function(id_sbm, fields) {
  // from: http://coursesweb.net/ajax/
  var phpcheck = 'check.php';  // Here add the php file that validate the form element
  var elm_sbm = document.getElementById(id_sbm);  // the submit button
  var fields = fields || [];  // store the fields ID
  var elm_v = {};  // store items with "elm_name:value" (to know when it is changed)
  var err = {};  // stores form elements name, with value of -1 for invalid, value 1 for valid, and 0 for not checked

  // change the css class of elm
  var setelm = function(elm, val) {
    // if val not empty, sets in err an item with element name, and value of 1
    // sets border to this form element,
    // else, sets in err an item with element name, and value of 0, and removes the border
    if(val != '') {
      err[elm.name] = -1;
      elm.className = 'errinp';
      if(elm_sbm) elm_sbm.setAttribute('disabled', 'disabled');  // disables the submit
      elm.parentNode.querySelector('.err').innerHTML = val;  //  adds the error message
    }
    else {
      err[elm.name] = 1;
      elm.className = 'vinp';
      elm.parentNode.querySelector('.err').innerHTML = '';  //  removes the error message

      // check if invalid or not checked items in $err (with value not 1)
      var inv = 0;
      for(var key in err) {
        if(err[key] != 1) {
          inv = 1;
          break;
        }
      }

      // if not invalid element, enables the submit button, and sends the form
      if(inv == 0 && elm_sbm) {
        elm_sbm.removeAttribute('disabled');
        elm_sbm.form.submit();
      }
    }
  }

  // sends data to a php file, via POST, and displays the received answer
  var checkAjax = function(elm) {
    if(elm.value != '' && (!elm_v[elm.name] || elm_v[elm.name] != elm.value)) {
      elm_v[elm.name] = elm.value;  // store name:value to know if was modified
      var xmlHttp =  (window.ActiveXObject) ? new ActiveXObject('Microsoft.XMLHTTP') : new XMLHttpRequest();  // gets the XMLHttpRequest instance

      // create pairs index=value with data that must be sent to server
      var  datatosend = elm.name +'='+ elm.value;
      xmlHttp.open("POST", phpcheck, true);      // set the request to php file

      // adds  a header to tell the PHP script to recognize the data as is sent via POST
      xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
      xmlHttp.send(datatosend);     // calls the send() method with datas as parameter

      // Check request status
      xmlHttp.onreadystatechange = function() {
        if(xmlHttp.readyState == 4) setelm(elm, xmlHttp.responseText);
      }
    }
    else if(elm.value =='') setelm(elm, 'This field must be completed.');
  }

  // register onchange event to form elements that must be validated with PHP via Ajax
  for(var i=0; i<fields.length; i++) {
    if(document.getElementById(fields[i])) {
      var elm = document.getElementById(fields[i]);
      err[elm.name] = 0;  //store fields-name in $err with value 0 (not checked)
      elm.addEventListener('change', function(e){ checkAjax(e.target);});
    }
  }
}

/* USAGE */
// array with IDs of the fields to validate
var fields = ['exname', 'expass', 'exmail'];

// create an object instance of checkFormElm(), passing the ID of the submit button, and the $fields
var chkF = new checkFormElm('exsbm', fields);
</script>

• In this example, the PHP script that checks and validates the form field value is added in "check.php" file.
Here is a php code that validate the Name, Password, and E-mail. You can create the PHP script to check the input field value according to your needs, with data stored on your server. The PHP response must be an empty string when the value is valid.
<?php
// http://coursesweb.net/php-mysql/

// array with error messages for each input field
$err = array(
  'exname'=>'Not registered name.',
  'expass'=>'Incorrect password.',
  'exmail'=>'Invalid email address.'
);
$reout = '';         // data to return

// Valided values for name, password, email
$name = 'coursesweb';
$password = 'mypass';
$email = 'me@domain.com';

// validate the POST values
if(isset($_POST['exname']) && $_POST['exname'] != $name) $reout = $err['exname'];
else if(isset($_POST['expass']) && $_POST['expass'] != $password) $reout = $err['expass'];
else if(isset($_POST['exmail']) && $_POST['exmail'] != $email) $reout = $err['exmail'];

echo $reout;

• Now we set CSS code to style the error message, and the input fields for when they are invalid, and validated:
/* style for validated field */
.vinp {
 background: #efeffe;
 border: 1px solid blue;
}

/* style for invalided field */
.errinp {
 background: #fefbda;
 border: 2px dashed red;
}

/* style for error message */
.err {
 margin: 0 5px;
 color: red;
 font-style: italic;
}

Daily Test with Code Example

HTML
CSS
JavaScript
PHP-MySQL
Which tag is a block element?
<div> <img> <span>
<div>Web Programming and Development</div>
Which CSS code displays the text underlined?
font-style: italic; text-decoration: underline; font-weight: 500;
h2 {
  text-decoration: underline;
}
Click on the JavaScript function that can access other function after a specified time.
insertBefore() setTimeout() querySelector()
function someFunction() { alert("CoursesWeb.net"); }
setTimeout("someFunction()", 2000);
Click on the instruction that returns the number of items of a multidimensional array in PHP.
count($array) count($array, 1) strlen()
$food = array("fruits" => array("banana", "apple"), "veggie" => array("collard", "pea"));
$nr_food = count($food, 1);
echo $nr_food;       // 6
Check and Validate input field when loses focus, with PHP via Ajax

Last accessed pages

  1. Bear Zuma (347)
  2. Zuma Games (2928)
  3. The Rise Of Atlantis (343)
  4. Making DIV Contents Scroll Horizontally, with multiple Div`s inside (4621)
  5. Lucky Balls (159)

Top accessed pages

  1. Courses Web: PHP-MySQL JavaScript Ajax HTML CSS Flash-AS3 (46193)
  2. Read Excel file data in PHP - PhpExcelReader (34685)
  3. PHP-MySQL free course, online tutorials PHP MySQL code (34542)
  4. Get Attribute (ID, Class, Name, Title, Src) with jQuery (31135)
  5. PHP PDO - exec (INSERT, UPDATE, DELETE) MySQL (28363)