Can anyone assist me in validating a contact form?

I've been attempting to integrate input validation functions with the submit function to create a fully functional and straightforward contact form that reacts appropriately to both correct and incorrect input types, as well as empty fields. I'm using Bootstrap 4 and have read the documentation on validation, but am baffled as to why the contact form still gets sent even if only one field is filled out and it doesn't require an email address :/. As a beginner in JS, I'm struggling to figure this out and it's been frustrating me - stuck at this for 8 hours. The commented code in the script.js file is there because I've been trying to combine various functionalities.

Is there anyone willing to rewrite these functions for me?

Below is the code for the form:

'use strict';
//---------Contact form SEND-----------
window.addEventListener("DOMContentLoaded", function () {
  // Fetch all the forms we want to apply custom Bootstrap validation styles to
  var forms = document.getElementsByClassName('needs-validation');  
  // get the form elements defined in your form HTML above
  var form = document.getElementById("bootstrapForm");
  // var button = document.getElementById("my-form-button");
  var status = document.getElementById("status");

  // Success and Error fn-s after form submission
  function success() {
    form.reset();
    status.classList.add("success");
    status.innerHTML = "Message has been successfully sent.";
  }

  function error() {
    status.classList.add("error");
    status.innerHTML = "There was a problem sending the message";
  }



  var validation = Array.prototype.filter.call(forms, function(form) {
    // handle the form submission event
    form.addEventListener('submit', function(e) {
      if (form.checkValidity() === false) {
        e.preventDefault();
        e.stopPropagation();
        var data = new FormData(form);
        ajax(form.method, form.action, data, success, error);
      }
      form.classList.add('was-validated');
    }, false);
  });
}, false);

// helper function for sending an AJAX request

function ajax(method, url, data, success, error) {
  var xhr = new XMLHttpRequest();
  xhr.open(method, url);
  xhr.setRequestHeader("Accept", "application/json");
  xhr.onreadystatechange = function () {
    if (xhr.readyState !== XMLHttpRequest.DONE) return;
    if (xhr.status === 200) {
      success(xhr.response, xhr.responseType);
    } else {
      error(xhr.status, xhr.response, xhr.responseType);
    }
  };
  xhr.send(data);
}









$(function()
{



    // Contact forms
    "use strict";

    // Detect when form-control inputs are not empty
    $(".cool-b4-form .form-control").on("input", function() {
      if ($(this).val()) {
        $(this).addClass("hasValue");
      } else {
        $(this).removeClass("hasValue");
      }
    });


});

Visit my website (with the form located at the bottom) to see it in action: https://marekcmarko.sk

Answer №1

As a newcomer, I am also unfamiliar with how to implement the functions you are requesting. However, based on the issue at hand, it appears that adding the "required" attribute directly to your HTML could potentially resolve the problem. This would prevent the form from being submitted if any fields are left empty. Additionally, utilizing the type attribute can assist in validating the correct input types.

<form>
        <div>
        <label for="Name">First Name:</label>
        <input id="Name" type="text" name="Name" placeholder="John" required>

        <label for="Last Name">Last Name:</label>
        <input id="Last Name" type="text" name="Last Name" placeholder="Smith" required>
        </div>

        <div>
        <label>
        Male
        <input type="radio" name="Gender" value="Male">
        </label>

        <label>
        Female
        <input type="radio" name="Gender" value="Female">
        </label>

        <label>
        Other
        <input type="radio" name="Gender" value="Other">
        </label>
        </div>

        <div>
        <label for="email">Email:</label>
        <input id="email" type="email" name="email" required>

        <label>
            Password:
            <input type="password" name="password" pattern=".{5,10}" required title="Enter  5 to 10 characters">
        </label>
        </div>


        <div>
        

        <fieldset>
            <legend>Birthday:</legend>
            <label for="month">Month:</label>
            <select name="month" id="month">
                <option value="january">Jan</option>
                <option value="february">Feb</option>
                <option value="march">Mar</option>
                <option value="april">Apr</option>
            </select>

            <label for="day">Day</label>
            <select name="day" id="day">
                <option value="1">1</option>
                <option value="2">2</option>
                <option value="3">3</option>
                <option value="4">4</option>
            </select>
            <label for="year">Year</label>
            <select name="year" id="year">
                <option value="2015">2015</option>
                <option value="2014">2014</option>
                <option value="2013">2013</option>
                <option value="2012">2012</option>
                <option value="2011">2011</option>
                <option value="2010">2010</option>
            </select>
        </fieldset>

        </div>
        
        <div>
        <label for="Terms">I agree to the terms and conditions</label>
        <input id="Terms" type="checkbox" name="Terms" value="x">
        </div>

        <button>Submit</button>
    </form>

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

Tips for loading internal JSON data using $http.get instead of using an external JSON file

I am currently facing an issue where I use a code snippet to load strings from an external json-file. While everything works fine, running the function locally triggers a 'cross origin' problem. As a solution, I attempted to input the strings dir ...

BufferGeometry: techniques for rendering face groupings

I have 2 different shapes and 2 sets of patterns. My primary objective is to sometimes hide a portion of the first shape (requiring 2 groups) while simultaneously displaying a section of the second shape (only needing 1 group). Prior to the r72 update, I u ...

Combining the contents of one HTML table with Bootstrap styling into another Bootstrap table

Check out the Bootstrap UI I created in the screenshot below: https://i.sstatic.net/NnZzI.png Here's the code. When a user clicks on the accept button in the new orders table, I want 'food 1' to move to the 'accepted' table. M ...

How can you use a single parameter in a JavaScript function to swap the values of two numbers

Here's the challenge I'm facing: I need to create a function that will output 5 when given a(0), and 0 when given a(5). a(0) = 5 a(5) = 0 It should look like this: Hint: Use the following function structure function A(num){} something ...

When transferring JavaScript Array via Ajax to PHP, it results in a null response

I am attempting to send a JavaScript array to PHP, but the post data keeps returning null. Here is my JavaScript code: console.log($Seats); console.log($Seats.toString()); console.log(JSON.stringify({ $Seats })); var jsonStr = JSON.stringify($Seats); $.a ...

Introducing a fresh counter variable inside a for loop

I'm currently working on a project with google-apps-script. My goal is to copy a row multiple times based on the number specified in a certain cell within a spreadsheet. For example, if B2 contains the number 6, I want to duplicate that row 6 times. I ...

Is there a way to transform data from a CSV format to a JSON format?

I've written the code to fetch data from a device in CSV format. Here are some sample data values: 1,1.635946,1.636609,1.640240,1.636091 2,1.642825,1.640267,1.639013,1.636568 3,1.636835,1.636022,1.637664,1.637144 4,1.641332,1.641166,1.637950,1.640 ...

The jsonGenerator is unable to process strings containing spaces

Hey, I'm having trouble passing a string with whitespaces to my JavaScript function using jsonGenerator. Here's the code snippet: jGenerator.writeStringField(cols[8], ap.getContentId() != null ? "<img src='img/active.png' onclick=au ...

Exclude a specific tag from a div in JavaScript

I need help selecting the text within an alert in JavaScript, excluding the <a> tag... <div id="addCompaniesModal" > <div class="alertBox costumAlertBox" style="display:inline-block;"> <div class="alert alert-block alert- ...

Issue with reactivity in deeply nested objects not functioning as expected

Currently, I am utilizing Konvajs for my project. In simple terms, Konvajs provides a canvas for drawing and editing elements such as text nodes that can be manipulated by dragging and dropping. These nodes are organized within groups, which are then added ...

Is it possible to pass multiple API props to a NextJs Page at once?

I am currently facing a challenge in rendering a page that requires data from two different API fetches. The URL in the address bar appears as: http://localhost:3000/startpage?id=1 Below is the code snippet for the first API fetch: import { useRouter } f ...

Having trouble loading CSS in an express view with a router

I am encountering an issue where I am unable to load my CSS into a view that is being rendered from a Router. The CSS loads perfectly fine for a view rendered from app.js at the root of the project directory. Below is my current directory structure, node_ ...

What is the process for exporting a class and declaring middleware in TypeScript?

After creating the user class where only the get method is defined, I encountered an issue when using it in middleware. There were no errors during the call to the class, but upon running the code, a "server not found" message appeared. Surprisingly, delet ...

Is there a way to determine the monitor's frame rate using JavaScript?

Could JavaScript be used to determine the refresh rate of a monitor, typically set at 60Hz for most LCD monitors? Is there a method available to execute a function after a specific number of frames have passed? There has been some curiosity about my reaso ...

Verify the user that is currently signed in

I am currently in the process of developing a custom middleware to facilitate user login in my application. Here is the function I have implemented for this purpose: async function authorizeUser(username, password) { try { const hashedPwd = aw ...

Encountering an issue while attempting to transmit Electron window data

Hey there! I'm currently in the process of transitioning my project from a web browser to a GUI-based app using electron. I came across this video which was really helpful in getting started. The tutorial uses yarn, but I prefer npm 9.2.0. Initially, ...

Are there any potential performance implications to passing an anonymous function as a prop?

Is it true that both anonymous functions and normal functions are recreated on every render? Since components are functions, is it necessary to recreate all functions every time they are called? And does using a normal function offer any performance improv ...

`Is there a way to adjust the column height in bootstrap?`

Hi there! I'm a beginner in AngularJS and Bootstrap. I've been using col-md-4 and repeating this div until I retrieve the data from JSON. My issue arises when I use the accordion with headings and drop-down lists. Everything works fine if the num ...

Error encountered when AJAX/ASP.NET Core MVC/DevExtreme POST back results in a faulty URL (Error/Error?code=22)

Incorporating Ajax into my MVC application allows me to initiate a POST request when the user clicks on the logout button. The goal is to redirect the user back to the Login page and route them to the HttpPost method in the controller. However, I encounter ...

Using async and await inside a setTimeout function within a forEach loop

Currently, I am facing a challenge with scheduling background jobs in Node.js. I need each job to run only after the previous one has finished. Below is the code snippet inside a function: jobArray.forEach((item, i) => { setTimeout(async () => { ...