How TO – JS Validation For Empty Fields


Previous


Next

Learn how to add form validation for empty input fields with JavaScript

Step 1) Add HTML:

Example

<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 an input field (fname) is empty, this function alerts a message, and returns false, to prevent the form from being submitted:

Example

<!DOCTYPE html>
<html>
<head>
<script>
function validateForm() {
var x = document.forms[“myForm”][“fname”].value;
if (x == “” || x == null) {
alert(“Name must be filled out”);
return false;
}
}
</script>
</head>
<body>

<h2>JavaScript validation for empty input field</h2>
<p>Try to submit the form without entering any text.</p>

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

</body>
</html>


Previous


Next

Scroll to Top