HTML tutorial
CSS3 tutorial
Bootstrap tutorial
JavaScript tutorial
JQuery tutorial
AngularJS tutorial
React tutorial
NodeJS tutorial
PHP tutorial
Python tutorial
Python3 tutorial
Django tutorial
Linux tutorial
Docker tutorial
Ruby tutorial
Java tutorial
C tutorial
C ++ tutorial
Perl tutorial
JSP tutorial
Lua tutorial
Scala tutorial
Go tutorial
ASP.NET tutorial
C # tutorial
Learn how to add form validation for empty input fields with JavaScript
Step 1) Add HTML:
<form name="myForm" action="/action_page" 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:
function validateForm() {
var x =
document.forms["myForm"]["fname"].value;
if (x == "") {
alert("Name must be filled out");
return false;
}
}
Try it Yourself »