verify html form previously to submit with php

I am using the script below to verify that the user enters the correct information on a registration page. Everything works FINE per individual field, and it displays an error message if there was an error entering the field information. The problem is that there are 5 different INPUT FIELDS, and the user might enter 3 correct and 2 incorrect, BUT IF THE USER GOES BACK AND CORRECT 1 FIELD (OF THE PREVIOUSLY 2 INCORRECT), and then submit the form THE FORM IS SUBMITTED WITH 1 FIELD ERROR.  How can I solve this issue NOT TO BE ABLE TO SUBMIT FORM IF AN ERROR ON FORM

Tnx, I have been trying to figure this for 5 days already :-(
I thought of a hidden field with value 0 for correct or 1 for incorrect, but that wouldn't solve the problem according to my previous example

I am using HTML and an external PHP to verify values

<script type="text/javascript">
    function ajaxFunction(disp_div) {
        var httpxml;
        try {
            // Firefox, Opera 8.0+, Safari
            httpxml = new XMLHttpRequest();
        } catch (e) {
            // Internet Explorer
            try {
                httpxml = new ActiveXObject("Msxml2.XMLHTTP");
            } catch (e) {
                try {
                    httpxml = new ActiveXObject("Microsoft.XMLHTTP");
                } catch (e) {
                    alert("Your browser does not support AJAX!");
                    return false;

        function stateChanged() {
            if (httpxml.readyState === 4) {

                document.getElementById(disp_div).innerHTML = httpxml.responseText;

        function getFormData(myForm) {
            var myParameters = new Array();
            val = "disp_div=" + disp_div;
            //// Userid  field data collection //
            var val = myForm.userid.value;
            val = "userid=" + val;
            //// email  field data collection //
            var val =;
            val = "email=" + val;
            // End of text field data collection //
            return myParameters.join("&"); // return the string after joining the array

        var url = "ajax-form-validation.php";
        var myForm = document.forms[0];
        var parameters = getFormData(myForm);
        httpxml.onreadystatechange = stateChanged;"GET", url, true);
        httpxml.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

Open in new window

Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Chris StanyonWebDevCommented:

Unless you have a compelling reason not to use it, I would really suggest you look at the jQuery library here. It's a very popular JS library and it makes sending AJAX requests a breeze. Load it up from a CDN it'll probably already be cached.

One you've got it loaded, then your JS script would look something like this:

$(function() {
    $('#myForm').submit(function(e) {
        $.post('ajax-form-validation.php', $(this).serialize(), function(response) {

Open in new window

It assumes you have a form with an ID of myForm. It then makes an AJAX request to your php script, and injects the response from that script into an element with an ID of response (such as a DIV).

You can then write your php script something like so:

$userid = isset($_POST['userid']) ? $_POST['userid'] : '';
$email = isset($_POST['email']) ? filter_var( $_POST['email'], FILTER_SANITIZE_EMAIL ) : '';

$errors = [];

// Validate the Email
if ( ! filter_var($email, FILTER_VALIDATE_EMAIL) ) {
    $errors[] = "Please enter a valid email address";

// Validate the UserID
if ( ! strlen($userid) > 3 ) {
    $errors[] = "User Id must be MORE than 3 char";

// Now build the response:
if ( count($errors) ) {

    echo "<div class='error'><ul>";
    foreach ($errors as $error) {
        printf("<li>%s</li>", $error);
    echo "</ul></div>";

} else {

    echo "<img src='tick.jpg'>";


Open in new window

You might also want to look at the jQuery Validate plugin. This will add some additional client-side validation to your page.

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Julian HansenCommented:
Firstly, read what Chris wrote and use jQuery for your AJAX - rather than reinventing the wheel. Makes your code cleaner and you are working of the back of tried and tested code that does so much of the heavy lifting for you.

Next - I would put the validation in a function. Here is an example of a general Validation function I use when processing server side script
function validateInput($data, $rules)
  $errors = [];
  foreach($rules as $k => $r) {
    if (empty($data[$k])) {
      $errors[$k] = "{$k} cannot be empty";
    else if (isset($r->len) && strlen($data[$k]) < $r->len) {
      $errors[$k] = "{$k} must be at least {$r->len} characters long";
    else if (isset($r->email) && !filter_var($data[$k], FILTER_VALIDATE_EMAIL)) {
      $errors[$k] = "{$k} must be a valid email address";
    else if (isset($r->regx) && !preg_match($r->regx, $data[$k])) {
      $errors[$k] = "{$k} is not in a valid format";
    else if (isset($r->numeric)) {
      if (!is_numeric($data[$k])) {
        $errors[$k] = "{$k} must be a number";
      else if ((isset($r->min) && $data[$k] < $r->min) || (isset($r->max) && $data[$k] > $r->max)){
        $errors[$k] = "{$k} not within allowable range";
  return $errors;

Open in new window

This is given as a quick example of the concept - you would need to tailor to your purposes.

You would pass this your data array ($_POST) and a Rules array - which might look something like this
$rules = [
  'firstName' => (object) ['len' => 3],
  'email' => (object) ['email' => true],
  'clientcode' => (object) ['regx' => '/^M(\d+){3}$/'],
  'age' => (object) ['numeric' => true, 'max' => 100, 'min' => 18]

Open in new window

You would then call it like this
$errors = validateInput($_POST, $rules);

Open in new window

Now you have a return of 0 or more errors. How you decide to proceed is entirely dependent on your application.

Personally I prefer to keep my view and server code separate - so while there is an argument for server side rendering I prefer to send back JSON and then let the view display the return as it needs to - this reduces the need to update the server when I decide to change my view code.

This would then manifest as follows

$errors = validateInput($_POST, $rules);
$resp = (object) [ 
  'status' => empty($errors), 
  'errors' => $errors
header('Content-Type: application/json');

Open in new window

On the client I would check the status of response from the AJAX call to see if it is false and if it has I then process the errors property of the return.

Because the returned error object has the field names as keys I can easily tell which field the error applies to.

You can test the code above here
1. Goto
2. In the API URL box enter
3. Select POST from Method
4. Set Return Type to JSON
5. Enter your data as URL Parameters - example (change to see different results)

Open in new window

6. Click run
crescueAuthor Commented:
Yeap right, why try to re-invent the wheel ! Is there a way to clear the input field value in case of an error ? Ex. inputid is wrong, then HTML 'INPUTID' field  value = "" (return value from PHP to HTML)

Chris StanyonWebDevCommented:
Generally with AJAX, you don't clear the fields when there's an error. You submit the form, validate at the server, and then return a list of errors to present to the user. It's then up to them to correct those errors before re-submitting. It's likely to be very annoying if the value you'd already entered into the input was cleared before you had a chance to correct it.
crescueAuthor Commented:
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Web Development

From novice to tech pro — start learning today.