Account
Categories

JavaScript onsubmit Event: Form Submission


Definition:

The onsubmit event validates the form data to make sure it is correct. If you use an onsubmit function on a form, it checks whether the input data is accurate. If the data is wrong, the browser shows an error message. If the data is validated, it is submitted successfully.

Now you will clearly understand with the help of the flowchart.

Start
   |
   v
Create Form (Name, Contact, Email, Message)
   |
   v
Add onsubmit Function --> [This function runs when the user clicks Submit]
   |
   v
User fills form
   |
   v
User clicks Submit
   |
   v
onsubmit Function runs
   |
   |-- Is Name correct? --No--> Show alert & Stop
   |-- Yes --> Is Contact correct? ...
   ...
   |
All correct --> Show "Form submitted successfully" --> Submit Form.
   |
   v
End
  

Syntax:

<form onsubmit="functionName()">
  <!-- form fields -->
</form>

Example:

// This function checks the form
function validateForm() {
let name = document.getElementById("name").value;
let contact = document.getElementById("contact").value;
let email = document.getElementById("email").value;
let message = document.getElementById("message").value;

if(name === "") {
alert("Please enter your name!");
return false;
}

if(contact === "" || isNaN(contact) || contact.length < 10) {
alert("Please enter a valid contact number!");
return false;
}

if(email === "" || !email.includes("@")) {
alert("Please enter a valid email!");
return false;
}

if(message === "") {
alert("Please enter your message!");
return false;
}

alert("Form submitted successfully!");
return true;
}

Output: