How to add form validation for empty input fields with JavaScript.
Step 1 : Create a Simple input field in HTML
<h2>Input field validation via JavaScript</h2>
<p>Press Submit button 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>
Step 2: Add JavaScript
function validateForm() {
var x = document.forms["myForm"]["fname"].value;
if (x == "" || x == null) {
alert("Name must be filled out");
return false;
}
}
Output and Full Code
You may Also Like
By Richard
/ April 29, 2022
How to Create an Off-Canvas Menu / Side Bar Navigation Step 1) Add HTML: <div id="mySidenav" class="sidenav"> <a href="javascript:void(0)" class="closebtn"...
Read More
By Richard
/ April 19, 2022
How To Create a Coming Soon Page / Maintenance Page Using HTML, CSS and JavaScript Step 1 : Adding...
Read More
By Richard
/ April 2, 2022
How to Create Weight Converter using HTML and JavaScript For Converting Pounds to Kilogram Adding HTML : <h2>Weight Converter Pound...
Read More
By Richard
/ February 19, 2022
How to create a Scroll indicator with CSS and JavaScript Step 1) Add HTML: <div class="header"> <h2>Scroll Indicator</h2> <div...
Read More
By Richard
/ February 15, 2022
Many a times, there is necessity of converting Color image into Black and White or Grayscale. Here in this very...
Read More
By Richard
/ February 4, 2022
There are many a times, when you’re going to need a countdown clock for your project. You may have an...
Read More
By Richard
/ January 20, 2022
How to Create an Avatar image with CSS Step 1) Add HTML: <h2>How to create Avatar Images with CSS</h2> <img...
Read More
By Richard
/ January 13, 2022
How to Change Background Images on Scroll with CSS. Step 1) Add HTML: <div class="bg-image img1"></div> <div class="bg-image img2"></div>...
Read More
By Richard
/ January 3, 2022
How to hide a Navigation Menu on Scroll down with CSS and JavaScript Step 1) Add HTML: Create a navigation...
Read More
By adaptabiz
/ December 21, 2021
What is Drupal ? Drupal is free, open source software that can be used by individuals or groups of users,...
Read More