Troubleshooting issues with form validation using if statements

Currently tackling a form validation challenge for a university project and hitting some roadblocks in the process. My attempts to use if statements within a function to validate the first-name input seem fruitless, as I'm not getting any response. Additionally, tweaking the 'href' link of the form element doesn't yield any results either. Any help would be greatly appreciated!

Check out JsFiddle for more details: https://jsfiddle.net/gcdb2nj3/2/

var form = document.querySelector('form');
var firstName = document.getElementById('first-name');
var lastName = document.getElementById('last-name');
var eMail = document.getElementById('e-mail');
var phoneNumber = document.getElementById('phone-number');
var textArea = document.getElementById('custom-text-area');
var warning = document.querySelector('.warning');

// Function to Prevent Default

function preventtDefault(e) {
    e.preventDefault();
};

validateForm();

function validateForm() {
    form.addEventListener('submit', function(e) {

        if(firstName.value === "") {
            warning.style.display="block"
            firstName.classList.add('input-invalid')
            e.preventDefault();
        } else {
            warning.style.display="none"
            e.preventDefault();
        }


    });
};

Answer №1

To prevent the default action, make sure to pass the event object to your preventDefault function. The code provided should work correctly because it calls event.preventDefault when form validation fails. In the JSFiddle example, preventDefault is called without any arguments.

// Custom Burger Menu Section


var sideNav = document.getElementById('mySidenav');
var burgerIcon =  document.querySelector('.burger-lines');
var closeBtn = document.querySelector('.closebtn');
var logo = document.querySelector('.logo');
var description = $('.what');

$(burgerIcon).on('click', function openNavigation() {
    sideNav.style.width="100%";
    sideNav.style.opacity="1";
    burgerIcon.style.opacity="0"
    closeBtn.style.color="white"
    closeBtn.style.fontSize="66px"
    closeBtn.style.top="-29px"
});


$(closeBtn).on('click', function closeNavigation() {
    sideNav.style.width="0";
    sideNav.style.opacity = ".00775";
    burgerIcon.style.opacity="1"
});

// Validate Form Fields

var formData = document.querySelector('form');
var firstNameInput = document.getElementById('first-name');
var lastNameInput = document.getElementById('last-name');
var emailInput = document.getElementById('e-mail');
var phoneInput = document.getElementById('phone-number');
var messageInput = document.getElementById('custom-text-area');
var feedbackMsg = document.querySelector('.warning');

// Function to Prevent Default Action

function handlePreventDefault(e) {
    e.preventDefault();
};

validateForm();

function validateForm() {
    formData.addEventListener('submit', function(e) {
        
        if(firstNameInput.value === "") {
            feedbackMsg.style.display="block"
            firstNameInput.classList.add('input-invalid')
            handlePreventDefault(e);
        } else {
            feedbackMsg.style.display="none"
            handlePreventDefault(e);
        }
        
        
    });
};
* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

body {
    background: #FCFCFC;
}


.sidenav {
    font-family: 'Cormorant Garamond';
    font-weight: bold;
    width: 0px;
    height: 100%;
    position: fixed;
    z-index: 1;
    top: 0;
    left: 0;
    background-color: rgba(0, 0, 0, 0.8);
    overflow-x: hidden;
    padding-top: 65px;
    margin-left: 0px;
    text-align: center;
    transition: .7s;
}

.sidenav a {
    padding: 45px 8px 20px 32px;
    text-decoration: none;
    font-size: 28px;
    color: white;
    display: block;
    transition: 0.7s;
}


.sidenav a:hover {
    color: rgb(155, 155, 155);
}

.burger-lines {
    font-size:30px;
    cursor:pointer;
    position: fixed;
    top: 44px;
    right: 70px;
}

.logo {
    font-family: 'Oswald', sans-serif;
    padding: 40px 0px 0px 40px;
    text-decoration: none;
    font-size: 26px;
    color: black;
    display: block;
    position: fixed;
    z-index: 1;
    top: 5px;
}



.sidenav .closebtn {
    color: black;
    cursor:pointer;
    position: absolute;
    top: -5px;
    right: 60px;
    font-size: 46px;
}


.headline-2 {
    text-transform: uppercase;
    text-align: center;
    position: relative;
    top: 9.5rem;
    right: 15rem;
    font-size: 18px;
}

.form-wrap {
    text-align: center;
    margin-top: 10rem;
}

.form-wrap > input {
    font-family: 'Cormorant Garamond';
    margin-top: 20px;
    padding: 5px;
    font-size: 16px;
    border: 1px solid lightgray;
    background: #FCFCFC;
}

#first-name, #last-name, #e-mail, #phone-number {
    width: 350px;
    height: 40px;
}

#custom-text-area {
    font-family: 'Cormorant Garamond';
    padding: 10px;
    margin-top: 1rem;
    width: 707px;
    height: 230px;
    font-size: 16px;
    background: #FCFCFC;
    border: 1px solid lightgray;
}

#submit {
    background: black;
    border: 1px solid black;
    font-size: 19px;
    text-align: left;
    color: white;
    width: 120px;
    height: 45px;
    margin-right: 29.3rem;
    margin-top: 25px;
}


#submit:hover {
    background: rgb(53, 53, 53);
    transition: .5s;
}

/*input:hover, #custom-text-area:hover {
    border: 1px solid red;
    color: red;
    transition: .5s ease-in;
}*/

.input-invalid {
    border: 1px solid red;
    color: red;
    transition: .5s ease-in;
}


.warning {
    font-family: 'Cormorant Garamond';
    color: red;
    position: relative;
    top: -36px;
    left: -3rem;
    display: none;
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Styx Somnus || Contact</title>
    <link rel="stylesheet" href="css/style.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ef8e8186828e9b8ac18c9c9cafdcc1dac1dd">[email protected]</a>/animate.min.css">
    <link href="https://fonts.googleapis.com/css?family=Oswald" rel="stylesheet"> 
    <link href="https://fonts.googleapis.com/css?family=Fjalla+One" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css?family=Cormorant+Garamond:400,700" rel="stylesheet"> 
    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.2.0/css/all.css" integrity="sha384-hWVjflwFxL6sNzntih27bfxkr27PmbbK/iSvJ+a4+0owXq79v+lsFkW54bOGbiDQ" crossorigin="anonymous">
</head>
<body>
    
    <header>
        <nav>

                <a class="logo" href="index.html">STYX SOMNUS</a>
    
                    <div class="sidenav" id="mySidenav">
    
                        <a href="javascript:void(0)" class="closebtn" >&times;</a>
                        <a href="index.html">Home</a>
                        <a href="about.html">About</a>
                        <a href="projects.html">Projects</a>
                        <a href="contact.html">Contact</a>
    
                    </div>
                <span class="burger-lines">&#9776;</span>
    
            </nav>
</header>

    <main>

        <p class="headline-2">Contact Form</p>


        <form action="#" class="form-wrap">

            <input type="text" id="first-name" placeholder="First Name*">
            <input type="text" id="last-name" placeholder="Last Name*"><br>
            <input type="email" id="e-mail" placeholder="Your E-Mail*">
            <input type="text" id="phone-number" placeholder="Phone Number"><br>
            <textarea id="custom-text-area" cols="40" rows="7" placeholder="Your Message..."></textarea><br>

            <input type="submit" id="submit" value="Submit     →">
            <p class="warning">All fields with * must be filled in.</p>

        </form>
    </main>


<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="js/main.js"></script>
</body>
</html>

Answer №2

It is important to remember to call preventDefault as soon as the form is submitted, perform validation checks, and proceed with submission only if validation is successful: https://jsfiddle.net/gcdb2nj3/4/

function validateForm() {
  form.addEventListener('submit', function(e) {
    e.preventDefault();

    if (firstName.value === "") {
      warning.style.display = "block"
      firstName.classList.add('input-invalid')
    } else {
      warning.style.display = "none"
      // submit form here
    }
  });
};

validateForm();

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

Is there a way to pass (req.param) using an input field and a button instead of manually entering it into the URL bar?

I'm attempting to collect input from the user and send it to the URL they specify. By combining it with url = "http://localhost:3000/"+":userInput" First, I attempted to gather user input and create a link using DOM methods <script> function m ...

Setting the color of an element using CSS based on another element's style

I currently have several html elements embedded within my webpage, such as: <section id="top-bar"> <!-- html content --> </section> <section id="header"> <!-- html content --> </section> <div id="left"> &l ...

React error: You have attempted an invalid hook call. Hooks are only allowed to be called within the body of a function component. What could be causing this issue with my syntax

In setting up a Login Form Page function, my goal is to determine whether the user is already logged in. If they are logged in, a button should be displayed prompting them to log out. The code snippet I am using for this functionality is: {user ? userLogge ...

Steps for transforming text into a clickable button hyperlink

I extracted data from a table using the Google API and successfully displayed all the information. Now, I'm looking to target specific columns containing text that are actually URLs and convert them into clickable buttons. Although I was able to styl ...

Exploring Inner Elements with jQuery Click Function

Here is a link to my interactive code example: http://jsfiddle.net/zqegh7yz/1/. The HTML markup in the example looks like this: <ul class="list"> <li class="clickable">item 1 <ul> <li>subitem 1</li> ...

What is the rationale behind calling the open() and send() functions after the anonymous function() in the following code snippet?

function fetchData() { var request = new XMLHttpRequest(); request.onreadystatechange = function() { if (request.readyState == 4 && request.status == 200) { document.getElementById("content").innerHTML = request.responseText; } } ...

Flask does not display images in CSS files

Starting with the frontend (HTML, CSS) of my project, I then proceeded to create a Flask file with the following code: from flask import Flask, render_template app = Flask(__name__) @app.route("/", methods=["GET"]) def index(): return render_templa ...

Facing Problem with Angular PUT Request - "Missing required request body"

I'm encountering a problem with my Angular application when attempting to send a PUT request to the server. The error message I receive reads "Required request body is missing." Below is a snippet of the code that is relevant: Within the Child Compo ...

What are some tips for incorporating Google Maps v3 with Twitter Bootstrap?

I'm looking to incorporate Twitter Bootstrap's Tabbed Menus into a Google Maps project that is currently coded entirely in javascript. The issue I'm facing is that since Twitter relies on jQuery, I'm unsure of how to effectively utilize ...

Guide to showing varied results depending on a textbox input in Javascript

In my grading system, the maximum score is 100 and it is automatically calculated based on the input provided. The total score is read-only. I also want to display a brief feedback text depending on the total score without using a submit button. For instan ...

Having issues with Jquery and duplicating tables functionality not functioning as expected

I am facing an issue with two external jQuery files. One file allows me to clone the last row of a table, while the other is supposed to retrieve the id of a select tag based on a class assigned to it. However, the second script only works for the original ...

Extract Information from a Website

Is there a way to extract data from another website using JavaScript and save it into a .TXT or possibly an XML file? If JavaScript is not the best solution, I am open to other suggestions. I am specifically interested in extracting the price and item na ...

React Application - The division is positioned centrally when run on local host, however, it does not retain its center alignment

I'm encountering an issue with deploying my create-react-app on github pages. The first image showcases my deployed app on github pages, but the image is not properly centered on the page as intended. https://i.stack.imgur.com/rOciT.jpg On the othe ...

Icon Stacking - overlaying icons on top of one another

I recently implemented a Google map in my React Native app. However, I'm facing an issue where the icons on the map are overlapping each other instead of being positioned on either side. Despite trying various configurations, the result remains unchan ...

Update the content of a div using jQuery and AJAX by targeting a specific button ID

I am in the process of developing a website that functions as an interactive "choose your own adventure" game. The page will present users with a question along with three different choices represented as buttons. Upon selecting one of the options, jQuery ...

Send a list of integers created in a JavaScript function from a Razor view to a controller

Is it possible to transfer data from JS created select tags to the controller? Here is the function responsible for generating the select tags: function changeFunc() { var elements = document.getElementsByClassName('selector2'); while (el ...

What is the best way to stretch Font Awesome icons horizontally within a message box and incorporate an image into a uniform circle design using Bootstrap?

I have encountered two issues that I need help with. Firstly, following my tutorial did not result in pictures that are as uniform as the design. Here are the comparison pictures: the first one is from the tutorial and the second one is what I coded. htt ...

Internet Explorer 11 has a problem with excessive shrinking of flex items

I have a flexbox setup with a left and right section, each of equal width. The left side displays an image and the right side contains text. While this layout works fine in Google Chrome, it does not wrap properly in Internet Explorer 11 when the width is ...

Preventing the detection of a jshint "error"

When creating an object using the constructor X, I later add multiple methods in the file using X.prototype.method = function () {...}. Although technically an assignment statement, it behaves like a function declaration, which typically doesn't requi ...

Ways to eliminate dates from the text of listed items

Before finalizing their registration, users on our site are shown a review page. This panel displays all the items they have selected, creating a unique and variable list for each individual. However, each item in the list starts with a distracting date/ti ...