0

I have a problem with submitting data with php after validate.js, I have tried a lot but I have failed. please look at the code below.

Here is the example HTML form.

<form id="main" action="#/shd.php" class="form-horizontal" method="post" novalidate>
          <div class="box-body">
            <div class="form-group">
              <label for="inputEmail3" class="col-sm-2 control-label">Name</label>

              <div class="col-sm-10">
                <input type="text" class="form-control"  name="name" id="name" placeholder="Complete Name" required="">
                <div class="col-sm-10  messages"></div>
              </div>
            </div>
          </div>
          <div class="box-footer">
            <button type="reset" class="btn btn-default">Cancel</button>
            <button type="submit" class="btn btn-success pull-right" >Submit</button>
          </div>

Here are the last lines of code of validate

  <script>
   (function() {
  validate.extend(validate.validators.datetime, {       
    parse: function(value, options) {
      return +moment.utc(value);
    },
    // Input is a unix timestamp
    format: function(value, options) {
      var format = options.dateOnly ? "YYYY-MM-DD" : "YYYY-MM-DD hh:mm:ss";
      return moment.utc(value).format(format);
    }
  });

  // These are the constraints used to validate the form
  var constraints = {
    name: {
      presence: true,
      length: {
        minimum: 3,
        maximum: 20
      },
      format: {
        pattern: "[a-z0-9]+",
        flags: "i",
        message: "can only contain a-z and 0-9"
      }
    }
  };

  // Hook up the form so we can prevent it from being posted
  var form = document.querySelector("form#main");
  form.addEventListener("submit", function(ev) {
    ev.preventDefault();
    handleFormSubmit(form);
  });

  // Hook up the inputs to validate on the fly
  var inputs = document.querySelectorAll("input, textarea, select")
  for (var i = 0; i < inputs.length; ++i) {
    inputs.item(i).addEventListener("change", function(ev) {
      var errors = validate(form, constraints) || {};
      showErrorsForInput(this, errors[this.name])
    });
  }

  function handleFormSubmit(form, input) {
    // validate the form aainst the constraints
    var errors = validate(form, constraints);
    // then we update the form to reflect the results
    showErrors(form, errors || {});
    if (!errors) {
      showSuccess();
    }
  }

  // Updates the inputs with the validation errors
  function showErrors(form, errors) {
    // We loop through all the inputs and show the errors for that input
    _.each(form.querySelectorAll("input[name], select[name]"), function(input) {
      // Since the errors can be null if no errors were found we need to handle
      // that
      showErrorsForInput(input, errors && errors[input.name]);
    });
  }

  // Shows the errors for a specific input
  function showErrorsForInput(input, errors) {
    // This is the root of the input
    var formGroup = closestParent(input.parentNode, "form-group")
      // Find where the error messages will be insert into
      , messages = formGroup.querySelector(".messages");
    // First we remove any old messages and resets the classes
    resetFormGroup(formGroup);
    // If we have errors
    if (errors) {
      // we first mark the group has having errors
      formGroup.classList.add("has-error");
      // then we append all the errors
      _.each(errors, function(error) {
        addError(messages, error);
      });
    } else {
      // otherwise we simply mark it as success
      formGroup.classList.add("has-success");
    }
  }

  // Recusively finds the closest parent that has the specified class
  function closestParent(child, className) {
    if (!child || child == document) {
      return null;
    }
    if (child.classList.contains(className)) {
      return child;
    } else {
      return closestParent(child.parentNode, className);
    }
  }

  function resetFormGroup(formGroup) {
    // Remove the success and error classes
    formGroup.classList.remove("has-error");
    formGroup.classList.remove("has-success");
    // and remove any old messages
    _.each(formGroup.querySelectorAll(".help-block.error"), function(el) {
      el.parentNode.removeChild(el);
    });
  }

  // Adds the specified error with the following markup
  // <p class="help-block error">[message]</p>
  function addError(messages, error) {
    var block = document.createElement("p");
    block.classList.add("help-block");
    block.classList.add("error");
    block.innerText = error;
    messages.appendChild(block);
  }

  function showSuccess() {
    // We made it \:D/
    alert("Success!");       
    return true;

  }
})();
</script>

When I click the Submit button after validating nothing happen!!, Anybody with experience with this validata.js code, please your idea.

4
  • don't use alert use console.log(). Then, you cad add e.preventDefault() when you click on button submit. when you finish the validation you submit the form. Commented Oct 26, 2018 at 14:42
  • sorry @Sfili I can't get you please try to show me an example so that I can understand Commented Oct 26, 2018 at 14:58
  • i'll write you an answer so you can read better the code Commented Oct 28, 2018 at 7:49
  • Sorry @Sfill_81, I have posted all the codes. can you provide your answer from there? Commented Oct 28, 2018 at 11:35

1 Answer 1

1

So you can do something like this

function submitForm( e ) {   
     e.preventDefault();
     //DO your validation stuff
     //if validation === TRUE
     $('#main').submit();// only this line was the solution.
};

So with preventDefault the default action of the event will not be triggered and when you click on the submit button you can do the validation before sending the data.

Sign up to request clarification or add additional context in comments.

2 Comments

Sorry @Sfill_81, I have posted all the codes. can you provide your answer from there?
Have you check your browser console?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.