Using form onsubmit for Input Validation in JavaScript
Using <form onsubmit> for Input Validation in JavaScript
How did I encounter this
When implementing a search bar for GTPS blog, I needed to ensure that empty submissions are prevented. While the
required attribute on an <input> element can help, it only works if the form is actually submitted through standard browser behavior. If a JavaScript function is used instead (such as calling fetch() directly), the required attribute alone won't stop an empty request from being sent.A clean and reliable way to handle this is to use a <form> with the onsubmit event and control the behavior using JavaScript.
✅ Example: HTML Structure
<form onsubmit="searchGame(event)"> <input type="text" id="searchKeyword" name="searchKeyword" required> <button type="submit">Search</button></form>
-
The
requiredattribute ensures that the input is not empty before submission. -
The
onsubmithandler calls a JavaScript function namedsearchGame.
✅ JavaScript Function
function searchGame(event) { event.preventDefault(); // Prevent default form submission (page reload)
const keyword = document.getElementById('searchKeyword').value.trim(); if (!keyword) return; // extra safety check
// Continue with the request (e.g., fetch) fetch(`/api/search?keyword=${encodeURIComponent(keyword)}`) .then(response => response.json()) .then(data => { // Handle the result console.log(data); }) .catch(error => console.error('Search error:', error));}
Why This Works
-
event.preventDefault()stops the browser from submitting the form and reloading the page. -
The
requiredattribute is honored because the browser still treats this as a form submission. -
JavaScript takes control after validation, allowing full flexibility for handling the request.
Comments
Post a Comment