DR01D
DR01D

Reputation: 1365

How to submit form using JS inside validator function

Typically forms are instructed where to post when the form element is declared.

For example something like this,

<form action="http://127.0.0.1:3000/myApp" method="POST">

However if I use JavaScript to validate the form before it is posted I'm not sure what to do.

The simplified test code below checks to see if the text input element is empty. If the input element wasn't filled in it alerts the user that the form wasn't valid. If it's not empty it should send the form's contents to node. But I'm not sure how to do this from inside a function. I'm going to use Express but I'm at the initial stage of setting this up.

"use strict";

function submitIfValid() {
    if(document.querySelector('input').value != '') {
        // The form is valid.  What instruction sends it to node?        
    } else {
        alert('form not valid');
    }
}
<form onsubmit="submitIfValid()">

    <input type="text" name="fieldOne"><br>

    <input type="submit">

</form>

Upvotes: 1

Views: 25

Answers (1)

Luca Kiebel
Luca Kiebel

Reputation: 10096

Just call .submit() on the form, this will handle submitting it, and not trigger the onsubmit handler again.

"use strict";

let form = document.querySelector("#form");

form.addEventListener("submit", submitIfValid)

function submitIfValid(event) {
    event.preventDefault();
    if(document.querySelector('input').value != '') {
        form.submit();
    } else {
        alert('form not valid');
    }
}
<form id="form" action="http://127.0.0.1:3000/myApp" method="POST">

    <input type="text" name="fieldOne"><br>

    <input type="submit">

</form>

You also need to use event.preventDefault() so the form doesn't submit even though it's not validated.

If you would like submit the form in the background, use fetch to make a POST request to the action:

"use strict";

let form = document.querySelector("#form");

form.addEventListener("submit", submitIfValid)

function submitIfValid(event) {
  event.preventDefault();
  if (document.querySelector('input').value != '') {
    const data = new URLSearchParams();
    for (const pair of new FormData(form)) {
      data.append(pair[0], pair[1]);
    }

    fetch(url, {
        method: 'post',
        body: data,
      })
      .then(...);
  } else {
    alert('form not valid');
  }
}
<form id="form" action="http://127.0.0.1:3000/myApp" method="POST">

  <input type="text" name="fieldOne"><br>

  <input type="submit">

</form>

Upvotes: 1

Related Questions