We help IT Professionals succeed at work.

verify html form previously to submit with php

crescue
crescue asked
on
140 Views
Last Modified: 2018-09-23
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;
            myParameters.push(val);
            //// Userid  field data collection //
            var val = myForm.userid.value;
            val = "userid=" + val;
            myParameters.push(val);
            //// email  field data collection //
            var val = myForm.email.value;
            val = "email=" + val;
            myParameters.push(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;
        httpxml.open("GET", url, true);
        httpxml.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        httpxml.send(parameters);
    }
</script>

Open in new window

ajax-form-validation.php
Comment
Watch Question

CERTIFIED EXPERT
Most Valuable Expert 2018
Distinguished Expert 2019
Commented:
This one is on us!
(Get your first solution completely free - no credit card required)
UNLOCK SOLUTION
CERTIFIED EXPERT
Most Valuable Expert 2017
Distinguished Expert 2019

Commented:
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";
      }
    }
    /* ADD OTHER RULES YOU MAY NEEDED */
  }
  
  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');
die(json_encode($resp));

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 http://www.marcorpsa.com/ee/apitester.html
2. In the API URL box enter http://www.marcorpsa.com/ee/t3397.php
3. Select POST from Method
4. Set Return Type to JSON
5. Enter your data as URL Parameters - example (change to see different results)
firstName=bat&email=da@com.ct&clientcode=M123&age=199

Open in new window

6. Click run

Author

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)

Tnx
CERTIFIED EXPERT
Most Valuable Expert 2018
Distinguished Expert 2019

Commented:
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.

Author

Commented:
Tnx
Unlock the solution to this question.
Join our community and discover your potential

Experts Exchange is the only place where you can interact directly with leading experts in the technology field. Become a member today and access the collective knowledge of thousands of technology experts.

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.