Curriculum
Course: JavaScript Basic
Login

Curriculum

JavaScript Basic

JSHome

0/216
Text lesson

DOM Forms

JavaScript Form Validation

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.

JavaScript Example

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.

HTML Form Example

<form name=”myForm” action=”/action_page.php” onsubmit=”return validateForm()” method=”post”>
Name: <input type=”text” name=”fname”>
<input type=”submit” value=”Submit”>
</form>