JavaScript can be used for HTML form validation.
If a form field (such as fname) is empty, this function will show an alert message and return false to stop the form from submitting.
function validateForm() { let x = document.forms[“myForm”][“fname”].value; if (x == “”) { alert(“Name must be filled out”); return false; } } |
The function can be invoked when the form is submitted.
<form name=”myForm” action=”/action_page.php” onsubmit=”return validateForm()” method=”post”> Name: <input type=”text” name=”fname”> <input type=”submit” value=”Submit”> </form> |