<form name="myform">
  <label for="name">Name</label>
  <input name="name" type="text" onchange="validateOneInput(this)"/>
  <p id="errorMessage-name"></p>
  <label for="email">Email</label>
  <input name="email"  type="email" onchange="validateOneInput(this)"/>
  <p id="errorMessage-email"></p>
  <label for="website">Website</label>
  <input name="website" type="url" onchange="validateOneInput(this)"/>
  <p id="errorMessage-website"></p>

  <input type="button" value="submit" name="submit" onclick="submitForm()"/>
</form>
[id^="errorMessage"] {
  min-height:1em;
  color: red;
  font-size: 0.7rem;
  margin: 0 1rem;
}
input, p, label {
  font-size: 1rem;
  font-family: Helvetica, sans-serif;
}
input {
  box-sizing: border-box;
  padding: 0.5rem;
  margin: 1rem 1rem 0 1rem;
  width:300px;
}
p {
  width: 500px;
  margin-top:0.5rem;
}
label {
  display: block;
  margin-top:1.5rem;
}

function clearError(el) {
  document.getElementById("errorMessage-" + el.name).innerHTML = "";
}

function validateOneInput(el) {
  clearError(el);
  if (!el.value) {
    // display each error under input field
    document.getElementById("errorMessage-" + el.name).innerHTML =
      'The "' + el.name + '" field is empty';
    return false;
  } else if (el.name == "email" && el.value.indexOf("@") < 1) {
    // check for example if email field contains @ character
    document.getElementById("errorMessage-email").innerHTML =
      'The "email" field is invalid';
    return false;
  }
  return true;
}

function validate(el) {
  const form = document.forms["myform"];
  // add flag for error messages
  let validated = true;

  // check each of the field if any of them is empty
  for (let i = 0; i < form.length; i++) {
    // check individually all form elements except for submit input
    if (form[i].name !== "submit" && !validateOneInput(form[i])) {
      validated = false;
    }
  }
  return validated;
}

function submitForm() {
  if (validate()) {
    window.alert("form can be submitted");
  } else {
    window.alert("form can not be submitted");
  }
}

External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

This Pen doesn't use any external JavaScript resources.