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
Selected Reading
HTML form action and onsubmit validations with JavaScript?
HTML form validation is essential for ensuring data integrity before submission. The onsubmit event allows you to validate form data and prevent submission if validation fails.
How Form Validation Works
The onsubmit event handler must return true to allow submission or false to prevent it. When validation fails, the form submission is blocked.
Basic Validation Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Form Validation Example</title>
</head>
<body>
<form onsubmit="return validateForm()" method="GET" action="https://mail.google.com/mail/">
<label for="txtInput">Enter "gmail" to proceed:</label><br>
<input type="text" id="txtInput" placeholder="Type gmail here" required><br><br>
<input type="submit" value="Submit">
</form>
<script>
function validateForm() {
var inputValue = document.getElementById('txtInput').value.trim();
if (inputValue.toLowerCase() !== 'gmail') {
alert('Please enter "gmail" in the text box to continue.');
return false; // Prevents form submission
}
return true; // Allows form submission
}
</script>
</body>
</html>
Advanced Validation Example
Here's a more comprehensive validation example with multiple form fields:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Advanced Form Validation</title>
<style>
.error { color: red; font-size: 14px; }
.form-group { margin-bottom: 15px; }
input[type="text"], input[type="email"] {
padding: 8px;
width: 250px;
border: 1px solid #ccc;
}
</style>
</head>
<body>
<form onsubmit="return validateAdvancedForm()" method="POST" action="#">
<div class="form-group">
<label for="username">Username:</label><br>
<input type="text" id="username" name="username">
<div id="usernameError" class="error"></div>
</div>
<div class="form-group">
<label for="email">Email:</label><br>
<input type="email" id="email" name="email">
<div id="emailError" class="error"></div>
</div>
<div class="form-group">
<label for="password">Password:</label><br>
<input type="password" id="password" name="password">
<div id="passwordError" class="error"></div>
</div>
<input type="submit" value="Register">
</form>
<script>
function validateAdvancedForm() {
// Clear previous errors
clearErrors();
var isValid = true;
var username = document.getElementById('username').value.trim();
var email = document.getElementById('email').value.trim();
var password = document.getElementById('password').value;
// Username validation
if (username.length < 3) {
showError('usernameError', 'Username must be at least 3 characters long');
isValid = false;
}
// Email validation
var emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailRegex.test(email)) {
showError('emailError', 'Please enter a valid email address');
isValid = false;
}
// Password validation
if (password.length < 6) {
showError('passwordError', 'Password must be at least 6 characters long');
isValid = false;
}
return isValid;
}
function showError(elementId, message) {
document.getElementById(elementId).textContent = message;
}
function clearErrors() {
var errorElements = document.querySelectorAll('.error');
errorElements.forEach(function(element) {
element.textContent = '';
});
}
</script>
</body>
</html>
Key Validation Concepts
| Return Value | Form Behavior | Use Case |
|---|---|---|
true |
Form submits normally | All validation passes |
false |
Form submission prevented | Validation fails |
| No return | Form submits (treated as true) | No validation needed |
Best Practices
- Always trim whitespace from input values
- Use case-insensitive comparisons when appropriate
- Provide clear, specific error messages
- Clear previous error messages before revalidation
- Consider both client-side and server-side validation
Conclusion
Form validation with JavaScript's onsubmit event provides immediate feedback to users and prevents invalid data submission. Return false from your validation function to block form submission when validation fails.
Advertisements
