JavaScript Tutorial

Validate Forms with JavaScript

Use JavaScript to check for empty form inputs

Download

Follow along!

Test Form

Open the index.html file in your browser and click the sumbit button.

The form doesn't submit and a bubble pops up telling us to fill in the first form field.

We want to turn off the HTML validation. Javascript gives us more options.

Disable Default HTML

Open the index.html file from the folder you downloaded

Find the first form tag and add "novalidate" to the end of the attributes.

                
                    <form class="box" id="contactForm" novalidate>
                
            

Save the file and return to your browser

Refresh the page and click the submit button

Since we disabled the HTML validation, the form will submit with empty fields. To stop this we'll trap the submit event by adding to our script.js file.

Trap Submit EventL

Open the script.js in your text editor

Look for the following comment

                    
                        // function to validate form
                    
                

Add the following function below the comment

                    
                        // function to validate form
                        function validateForm(evt) {
                        }
                    
                

The evt parameter in the parenthesis is referencing the submit event inside the createEventListenrs function.

To trap the submit event and stop the form from submitting add the follow statement and comment to the validateForm function.

                    
                        // function to validate form
                        function validateForm(evt) {
                            evt.preventDefault(); // trap submit event
                        }
                    
                

Now we need to create our custom validation.

Setting Up Custom Validation

Go back to the script.js file and find the following comment:

                    
                        // Function to check for empty fields
                    
                

Add the following function below the comment.

                    
                        // Function to check for empty fields
                        function validateRequiredInputs() {
                        }
                    
                

Now we need to declare some variables. Add the following variables below the "global variables" comment.

                    
                        // global Variables
                        var formValidity = true;
                        var inputValid = true;
                    
                

We'll use these to track validity in our functions.

Now let's add the following local variables to our validateRequiredInputs() function.

                    
                        // Function to check for empty inputs
                        function validateRequiredInputs() {
                            var formInputs = document.querySelectorAll("#contactForm input"); // assign all contact inputs
                            var userMessage = document.querySelector("#userMessage"); // assign message div
                            var currentInput; // variable for current input
                        }
                    
                

We'll use these variables with our exception handling statements.

Exception Handling

We're going to use try/catch exception handling. This allows us to tell the program what to do with empty inputs.

Add the new lines below to your validateRequiredInputs() function.

                    
                        // Function to check for empty inputs
                        function validateRequiredInputs() {
                            var formInputs = document.querySelectorAll("#contactForm input"); // assign all contact inputs
                            var userMessage = document.querySelector("#userMessage"); // assign message div
                            var currentInput; // variable for current input

                            // check for empty inputs
                            try {
                                for (var i = 0; i < 3; i++) {
                                }
                            }
                        }
                    
                

The try block allows us to set conditions for the input field values. The for statement inside the try block is going to start a loop.

The for loop uses a counter variable: i (stands for index). This allows us to control the number of loops.

Inside the parenthesis of the for loop we have 3 statements. The first declares i as the counter variable. The second tells the loop to continue as long as i is less than 3. The third tells the loop to increment by positive 1.

The formInputs variable contains a node list. The length of this list is 3, but the range is 0-2. So the first input is 0 and the third input is 2. That's why the loop is set to run when i is less then 3.

Now we store the current loop input in currentInput variable and check it's value. Add the new lines below to the for loop block.

                    
                        // Function to check for empty inputs
                        function validateRequiredInputs() {
                            var formInputs = document.querySelectorAll("#contactForm input"); // assign all contact inputs
                            var userMessage = document.querySelector("#userMessage"); // assign message div
                            var currentInput; // variable for current input

                            // check for empty inputs
                            try {
                                for (var i = 0; i < 3; i++) {
                                    currentInput = formInputs[i]; // current input
                                    
                                    // apply border + input validity if empty
                                    if (currentInput.value === "") {
                                    currentInput.style.border = "1.5px solid red"; // apply border
                                    inputValid = false; // progress to throw
                                    }
                                }
                            }
                        }
                    
                

The if statement checks the value of the input field for an empty string (no user input). If the field is empty a red border is applied.

Remember the inputValid variable? False will be assigned to inputValid when the field is empty (we'll use this later).

Add the new lines below to the for block.

                    
                        // Function to check for empty inputs
                        function validateRequiredInputs() {
                            var formInputs = document.querySelectorAll("#contactForm input"); // assign all contact inputs
                            var userMessage = document.querySelector("#userMessage"); // assign message div
                            var currentInput; // variable for current input

                            // check for empty inputs
                            try {
                                for (var i = 0; i < 3; i++) {
                                    currentInput = formInputs[i]; // current input
                                    
                                    // apply border + input validity if empty
                                    if (currentInput.value === "") {
                                    currentInput.style.border = "1.5px solid red"; // apply border
                                    inputValid = false; // progress to throw
                                    } else {
                                        // reset Border and Input Validity
                                        currentInput.style.border = "";
                                        inputValid = true;
                                    }
                                }
                            }
                        }
                    
                

The else block will remove (or not apply) a border and set (or reset) the inputValid to true.

We need to add a throw statement to the try block. This will create a message that we can display.

Add the new lines below to the try block under the for block.

                    
                        // Function to check for empty inputs
                        function validateRequiredInputs() {
                            var formInputs = document.querySelectorAll("#contactForm input"); // assign all contact inputs
                            var userMessage = document.querySelector("#userMessage"); // assign message div
                            var currentInput; // variable for current input

                            // check for empty inputs
                            try {
                                for (var i = 0; i < 3; i++) {
                                    currentInput = formInputs[i]; // current input
                                    
                                    // apply border + input validity if empty
                                    if (currentInput.value === "") {
                                    currentInput.style.border = "1.5px solid red"; // apply border
                                    inputValid = false; // progress to throw
                                    } else {
                                        // reset Border and Input Validity
                                        currentInput.style.border = "";
                                        inputValid = true;
                                    }
                                }

                                // throw message if not valid
                                if (inputValid === false) {
                                    throw "Please fill the outlined fields";
                                }
                            }
                        }
                    
                

The if statement creates the throw string when the for block assigns "false" to the inputValid variable.

Add the new lines below to the validateRequiredInputs() function under the try block

                    
                        // Function to check for empty inputs
                        function validateRequiredInputs() {
                            var formInputs = document.querySelectorAll("#contactForm input"); // assign all contact inputs
                            var userMessage = document.querySelector("#userMessage"); // assign message div
                            var currentInput; // variable for current input

                            // check for empty inputs
                            try {
                                for (var i = 0; i < 3; i++) {
                                    currentInput = formInputs[i]; // current input
                                    
                                    // apply border + input validity if empty
                                    if (currentInput.value === "") {
                                        currentInput.style.border = "1.5px solid red"; // apply border
                                        inputValid = false; // progress to throw
                                    } else {
                                        // reset Border and Input Validity
                                        currentInput.style.border = "";
                                        inputValid = true;
                                    }
                                }

                                // throw message if not valid
                                if (inputValid === false) {
                                    throw "Please fill the outlined fields";
                                }
                            }

                            // if any input is empty show message
                            catch(msg) {
                            }
                        }
                    
                

We will use the catch block to display a message to the user and set the value of formValidity to false.

Displaying A Message To The User

The catch statement will grab the message (msg) from the throw string.

Add the lines below to the catch block.

                    
                        // if any input is empty show message
                        catch(msg) {
                            // apply css style
                            userMessage.style.border = "2px solid red";
                            userMessage.style.padding = "9px";
                            userMessage.style.marginBottom = "20px";

                            // show message
                            userMessage.textContent = msg;
                            formValidity = false; // no submit
                        }
                    
                

The userMessage uses the textContent property to add text to the div element at the top of the form

We are adding css style to the div element

Finally we are assigning false to the formValidity variable. This will help us later.

Return to the try block. Add the new else block below just after the if block.

                    
                        else {
                            // reset message div
                            userMessage.textContent = "";
                            userMessage.style.border = "";
                            userMessage.style.padding = "";
                            userMessage.style.marginBottom = "";
                        }
                    
                

This block will reset (or not apply) the message and the styling for the userMessage div.

Calling The validateRequiredInputs Function

Go back to the validateForm function and add the new lines from the following example.

                    
                        // function to validate form
                        function validateForm(evt) {
                            evt.preventDefault(); // trap submit event
                            formValidity = true; // reset form validity on button click
                            validateRequiredInputs(); // call function

                            // if validateRequiredInputs returns formValidity = true
                            if (formValidity === true) {
                                document.forms[0].submit(); // submit form
                            }
                        }
                    
                

Now we are reseting the formValidity when the user clicks the button. Only the validateRequiredInputs function should set this to false.

Then we are calling the validateRequiredInputs function to check the form inputs.

If the validateRequiredInputs function does not find empty inputs, the formValidity variable will remain true and the form will submit.

Download

Completed Work Along Files

For reference