JS Tutorial
JS Version
JS Objects
JS Function
JS Classes
JS Async
JS HTML DOM
JS Browser BOM
JS Web API
JS AJAX
JS JSON
JS vs JQUERY
JS Graphics
DOM Forms
JavaScript Form Validation
HTML form validation can be done by using JavaScript.
If a form field (fname) is empty, this function changes a message, and returns false, to avoid the form from being submitted.
Example
function validateForm() {
let x = document.forms[“myForm”][“fname”].value;
if (x == “”) {
alert(“Name must be filled out”);
return false;
}
}
The function can be called when the form is submitted.
HTML Form Example
<!DOCTYPE html>
<html>
<head>
<script>
function validateForm() {
let x = document.forms[“myForm”][“fname”].value;
if (x == “”) {
alert(“Name must be filled out”);
return false;
}
}
</script>
</head>
<body>
<h2>JavaScript Validation</h2>
<form name=”myForm” action=”/action_page.php” onsubmit=”return validateForm()” method=”post”>
Name: <input type=”text” name=”fname”>
<input type=”submit” value=”Submit”>
</form>
</body>
</html>
Output