Stop users from submitting empty forms

I'm facing an issue with my form where I want to prevent it from being submitted if the fields are blank and also highlight those blank fields. The code I currently have works when trying to submit with blank fields, but for some reason, it doesn't submit when the fields are filled out. I can't seem to figure out what's wrong. Any help would be greatly appreciated.

Here is the JavaScript code I am using:

function CheckFields(){
    if((document.getElementById('title').value=="") || (document.getElementById("textfield").value=="")){
        const formElement = document.querySelector('form');
        formElement.addEventListener('submit',event =>{
            event.preventDefault();

            alert("Please fill out all fields before submitting");
            document.getElementById("title").style.backgroundColor=red;
            document.getElementById("title").style.backgroundColor=red;
        });
    }

And here is the relevant HTML code:

<input name="post" type="submit" value="Post" onclick="CheckFields();">

Answer №1

Copied from: https://developer.mozilla.org/en-US/docs/Learn/Forms/Form_validation in order to provide a consistent answer for this question, given that the webpage content may be updated periodically.


Utilizing pre-built form validation One of the key advantages of HTML5 form elements is the capability to validate user input without the need for JavaScript. This validation is achieved by using specific attributes on form fields. Some common validation attributes include:

required: Indicating whether a field must be completed before submitting the form. minlength and maxlength: Setting minimum and maximum lengths for text data.

min and max: Defining minimum and maximum values for numerical inputs.

type: Specifying the expected format of the data, such as a number, email address, or other predefined type.

pattern: Describing a regular expression pattern that the entered data must adhere to.

Answer №2

Typically, validating fields in this manner is not considered best practice. However, the issue in your code lies in the order of the condition and form submit event. Here is how it should be structured:

var myForm = document.querySelector('form');
var myTitle = document.getElementById('title');
var myTextfield = document.getElementById('textfield');
myForm.addEventListener('submit', event=>{
     if(myTitle.value=="" || myTextfield.value==""){
         alert("Please fill out all fields before submitting the form");
         myTitle.style.backgroundColor=red;
         myTextfield.style.backgroundColor=red;
         return false;
     } else {
         return true;
     };
});

Answer №3

Enhance your input fields with the required attribute to enable client-side validation. For more robust validation, consider incorporating server-side validation through a model.

Observe the implementation of required:

            <form action="/action_page.php">
                <label for="fname">First name:</label><br>
                <input type="text" id="fname" name="fname" value="" required><br>
                <label for="lname">Last name:</label><br>
                <input type="text" id="lname" name="lname" value="Doe"><br><br>
                <input type="submit" value="Submit">
            </form>

Answer №4

There are numerous methods to validate a form. With Html 5 forms, you have the option to include 'required' for client-side validation. Server-side validation is another approach that can be utilized. Real-time form validation using ajax is also a popular choice. Additionally, focusing on a field can help highlight areas that have not been filled out.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Challenges arise with CSS alignment when adding d3.js charts to a webpage

I'm puzzled by the empty space that appears between the left column (highlighted in the image) and the header. This peculiar gap only seems to occur when the middle column is filled with a chart. I've scrutinized the code using Chrome Developer t ...

The fixed div with the z-index at the top isn't functioning properly

I need a div that remains fixed at the top of my page and overlaps any other elements on the page, similar to the blue search bar on Facebook. Currently, when I scroll down, the table ends up above the div, but I want it to be below the div instead. Here i ...

Is it possible to obtain the parameters using an empty object with the getStaticPaths function?

Within the getStaticPaths function, a path is returned with params postId:1. If additional params like postId: 2 or postId: 3 are included, they will also be statically generated. Is my understanding correct? Is there a way to avoid loading any post based ...

Tips for resizing all HTML elements when adjusting browser window dimensions

I am working with the following HTML code snippet: <div id="sectionOne" class="container-fluid d-flex flex-column justify-content-center align-items-center" style="height: 80vh;"> <div class="row d-flex justify-content-center" style="color: #00 ...

The React JSX error message "Maximum update depth exceeded" occurs when there

It appears that I am facing an issue of creating an infinite loop while passing props from one class to another. Despite ensuring that the buttons are correctly bound and trigger only once, the problem persists without any solution in sight after thorough ...

"Using SetState frequently results in multiple rerenders of the component

Currently, I am developing a messenger application with a main screen component that displays all messages. My goal is to make sure that whenever a user sends or receives a message, the component updates the Flatlist to show the latest sent message. To ach ...

Dealing with redirecting to the login page in Angular

I recently started working with Angular and I feel completely lost. My initial task involves making a simple Rest-GET request, but the destination is located behind an external login page. This results in my request being redirected to the external page a ...

What is the best way to implement a unique function in an angularjs directive?

Is it possible to execute a custom function when clicking on the checkbox of a table row shown below? I am using the Angular Smart Table directive and need to be able to store the rowid or another property of the rows when the checkbox is clicked. app.dir ...

problem arises when I attempt to use the code individually, as well as when I incorporate it into my existing

<!doctype html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width"> <title>App Title</title> <!-- Framework's CSS Fil ...

The issue with triggering button events in JavaScript

I've integrated a jquery modal popup for saving uploaded files related to a specific device. The modal appears, the cancel button functions correctly, but I am struggling to trigger the onclick event for the Save button... This is what I have impleme ...

Experience the sleek transparency when black hues grace the interface on iOS 14 and above

When implementing the code snippet below, .packages > .ulWrapper::after { background: linear-gradient( to left, var(--edge-color) 5%, rgba(0, 0, 0, 0) 95% ); /* option 1 - red */ background: linear-gradient( to left, var(--edg ...

"TypeScript Static Classes: A Powerful Tool for Struct

In my TypeScript code, there is a static class with an async build method as shown below: export default class DbServiceInit { public static myProperty: string; public static build = async(): Promise<void> => { try { ...

Unraveling AngularJS: Mastering the Art of Interpolating Interpol

Trying to interpolate a string retrieved from the database, such as "Users({{users_count || 0}})", poses a problem. Using {{}} or ng-bind for interpolation does not work properly. The HTML code written is {{data.usersCount}}, but instead of ren ...

Exploring the integration of PostgreSQL into JavaScript

As a beginner in JavaScript, I am looking to create a web page that can store data in a database. Can anyone provide guidance on what resources or materials I should study to learn more about this process? ...

Greetings: Obtaining an array of text within the <td> tags

Here is the HTML Source: <td bgcolor="#ffffbb" colspan=2><font face="Verdana" size=1>2644-3/4<br>QPSK<br><font color="darkgreen">&nbsp;&nbsp;301</font> - 4864</td> I am looking to extract text array wit ...

Combining Objects within an Array in JavaScript When Certain Conditions Are Satisfied

In my scenario, I am seeking assistance with merging the values of objects in an array if the id matches the warehouse_item_id. Specifically, there are two objects that need to be merged: id 191 and id 52 because id 52 has a warehouse_item_id of 191. Ple ...

Inserting a variable into a JSON string

Within my code, I have a basic variable containing strings that are converted into a JSON object. My goal is to create an input field where a person's name can be entered and added to the text. The current setup looks like this var text = '{"st ...

Transferring a Query between Domains with the Help of JavaScript

It is necessary to develop a function that generates a query based on the user's input of "Test" in an INPUT on Site A (SiteA.com) and then redirects to Site B within the same window, passing along the query (SiteB.com/search.aspx?k=test). Code snipp ...

Javascript cards arranged in descending order

I'm in the process of developing a sorting feature that arranges cards in the DOM from Z to A with the click of a button. Although I've successfully implemented the logic for sorting the array, I'm facing difficulties in rendering it. Withi ...

What is the best method for accessing a value in IndexedDB while utilizing service workers?

I am feeling overwhelmed by the concepts of IndexedDB and serviceworkers as I try to transform them into a functional application. Despite my extensive research, including studying various examples, I am struggling to integrate the two technologies effecti ...