Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
What is onsubmit event in JavaScript?
The onsubmit event is an event that occurs when you try to submit a form. You can put your form validation against this event type. The following example shows how to use onsubmit. Here we are calling a validate() function before submitting a form data to the web server. If validate() function returns true, the form will be submitted, otherwise, it'll not submit the data.
Syntax
<form onsubmit="return functionName()">
// form elements
</form>
// Or using JavaScript
form.onsubmit = function(event) {
// validation logic
return true; // or false
};
Example: Basic Form Validation
The following example shows a complete form validation using the onsubmit event:
<html>
<head>
<script>
function validate() {
var name = document.getElementById("name").value;
var email = document.getElementById("email").value;
if (name === "") {
alert("Name is required!");
return false;
}
if (email === "") {
alert("Email is required!");
return false;
}
alert("Form submitted successfully!");
return true;
}
</script>
</head>
<body>
<form onsubmit="return validate()">
<label>Name: </label>
<input type="text" id="name" name="name"><br><br>
<label>Email: </label>
<input type="email" id="email" name="email"><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
Using Event Object
You can also use the event object to prevent form submission:
<html>
<head>
<script>
function handleSubmit(event) {
var username = document.getElementById("username").value;
if (username.length < 3) {
event.preventDefault(); // Prevent form submission
alert("Username must be at least 3 characters long!");
return false;
}
alert("Form is valid and will be submitted!");
}
</script>
</head>
<body>
<form onsubmit="handleSubmit(event)">
<label>Username: </label>
<input type="text" id="username" name="username"><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
Key Points
- Return
falseor useevent.preventDefault()to stop form submission - Return
trueto allow normal form submission - The onsubmit event fires before the form data is sent to the server
- Perfect for client-side validation before server submission
Conclusion
The onsubmit event is essential for form validation in JavaScript. Use it to validate user input before submitting data to the server, preventing invalid submissions by returning false or using preventDefault().
