Avatar of crescue
 asked on

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 = myForm.email.value;
            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;
        httpxml.open("GET", url, true);
        httpxml.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

Open in new window

Web DevelopmentHTMLPHPJavaScript

Avatar of undefined
Last Comment

8/22/2022 - Mon
Chris Stanyon

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question
Julian Hansen

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 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)

Open in new window

6. Click run

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 Stanyon

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.
This is the best money I have ever spent. I cannot not tell you how many times these folks have saved my bacon. I learn so much from the contributors.