How to validate empty fields using JS

Learn how to add form validation for empty input fields using JavaScript.

Form validation for empty input fields

Step 1 - Add HTML:

<form name="myForm" action="/action_page.php" onsubmit="return validateForm()" method="post" required>
  Name: <input type="text" name="fname">
  <input type="submit" value="Submit">
</form>

Step 2 - Add JavaScript:

If the input field (fname) is empty, this function will display a warning message and return false to prevent the form from being submitted:

function validateForm() {
  var x = document.forms["myForm"]["fname"].value;
  if (x == "") {
    alert("Name must be filled out");
    return false;
  }
}

Try it yourself