Form validation has not passed the necessary checks

Struggling to create a new user POST form with Bootstrap form validation but encountering an issue. The button code is as follows:

<button class="btn btn-primary btn-addUser" type="submit">Add User</button>

This button triggers the creation of a new post using input data:

const addUsersBtn = document.querySelector(".btn-addUser");

// Handle click event for button
addUsersBtn.addEventListener("click", postNewUser);

// Function to perform POST request for new user
function postNewUser(e) {
  e.preventDefault();
  // Retrieve values from form inputs
  const name = form.elements.namedItem("name").value;
  const username = form.elements.namedItem("username").value;
  const email = form.elements.namedItem("email").value;
  const phone = form.elements.namedItem("phone").value;
  const website = form.elements.namedItem("website").value;

  // Create user object with input values
  const newPost = {
    name: name,
    username: username,
    email: email,
    phone: phone,
    website: website,
    user_id: `id_${Math.random() * Math.random()}`,
  };

  // Make API call to create a new post
  createPost(newPost, (response) => {
    const card = newPostTemplate(response);
    container.insertAdjacentElement("afterbegin", card);
    form.reset();
    initPopovers();
  });
}

The validation does not work when 'btn-addUser' class is present on the button. Removing this class allows validation to function normally. My addUser.js file contains:

// Get form element
const form = document.forms["addUser"];
// Function to create a new post
function createPost(body, callback) {
  return new Promise((resolve, reject) => {
    const request = new XMLHttpRequest();
    request.open("POST", "https://jsonplaceholder.typicode.com/posts");
    request.addEventListener("load", () => {
      const response = JSON.parse(request.responseText);
      if (request.status >= 400) {
        reject(request.response);
      } else {
        resolve(request.response);
      }
      callback(response);
    });
    request.setRequestHeader("Content-type", "application/json; charset=UTF-8");
    request.send(JSON.stringify(body));
  });
}
// Template for creating a new post
function newPostTemplate(post) {
  // Code omitted for brevity
}
// Add event listener to button for adding users
addUsersBtn.addEventListener("click", postNewUser);
// Function to handle user submission
function postNewUser(e) {
  // Code omitted for brevity
}

Questions:

  1. Is it possible to have two buttons, one with 'btn-addUser' class and one without? I want the button without the class to be disabled until successful validation, while the other button will automatically disable after clicking.
  2. Am I overcomplicating things and is there a simpler way to achieve this?

Answer №1

e.preventDefault() could be the reason why your form is not undergoing automatic validation checks by the browser when it's being submitted. It's important to manually verify if the form is valid by utilizing form.checkValidity() as shown below:

function validateForm(e) {
  e.preventDefault();

  if (form.checkValidity()) {
    // Proceed with form submission as it's valid
    // Add your specific logic here
  } else {
    // Display validation UI as the form is invalid
    // form.classList.add("was-validated");
  }
}

Ensure that your form contains necessary Bootstrap validation attributes and classes, such as including novalidate on the form element and applying appropriate validation classes on form inputs.

Answer №2

It's puzzling why you're resorting to such complex actions when simple validations could easily suffice by just adding the required attribute. Simpler methods are definitely available. Additionally, utilizing classes or id for this purpose is completely feasible. Ids, in particular, offer a more straightforward and unique solution. You have the option to disable an element by setting its attribute to "disabled", or simply hide it with some basic styling using "display:none;"

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

Adding numbers to a textbox using a JavaScript algorithm

There are two textboxes in this scenario. The first box should always contain 4 digits when you leave it, while the second box should always contain 10 digits. A javascript function needs to be implemented so that when a user leaves one of the textboxes, ...

Having trouble creating an alias system in discord.js and encountering errors

While developing an alias system for my Discord bot, I encountered a situation where I wanted to display the message: "if the user entered the wrong command name or alias then return: invalid command/alias". However, when implementing this logic, ...

Changing the 'null' string to null in JavaScript

Within an array of objects, some keys have a value of "null" as a string that I want to convert to null. Here is the code I tried: let obj = [{ "fundcode": "DE", "fundname": "Defens", ...

Acquiring HTML form data using JavaScript

Although it may seem trivial, I'm facing a challenge. I have an HTML form that is dynamically generated by JavaScript and populated with initial data fetched from the server. The form is displayed correctly with the pre-filled data. My goal is to allo ...

Send data by using a link tag in AngularJS

I am a beginner with angularJS and I am facing an issue while trying to create a custom button and attach it to my form instead of using a regular button. Despite trying multiple approaches, none of them seem to work well for me. When I press enter inside ...

Sending a form cancellation submission within a nested function call

I need help preventing my form from submitting in case the confirmation message is cancelled. How can I achieve this within the each() loop? $('#myForm').submit(function() { var inputs = $(this).find('input:checked'); inputs.ea ...

Using asynchronous functions in React Native still generates a promise despite the presence of the 'await' keyword

After making an API call, my react-native component is supposed to return some SVG. Despite using an async function with await, the function still returns a promise that has not resolved yet. I have seen similar questions asked before, but I am puzzled as ...

Refine the table by selecting rows that contain a specific value in the href attribute of the <a> tag, and display the parent row when the child row

I've been working on filtering and searching the table below based on the href value. My code successfully filters the displayed columns in the table, but it fails to work when I search for a string within the href attribute. For instance, if I searc ...

Displaying various elements with distinct properties in React using ES6

<---------------------MODIFICATION------------------------> I initially thought I needed multiple onChange functions, but after reviewing the answers provided, I discovered a solution thanks to the helpful user's response. With some experimenta ...

Prevent automatic scrolling by clicking when you reach the bottom

In order to replicate the issue I am experiencing, please click on the down button four times, and then click on the up button. You will observe that you need to click the up button one extra time for it to function properly. How can I detect when it has r ...

Tips for building a custom error handling function specifically designed for parsing and handling errors in

Is there a way to reduce redundancy in my code, such as: let name = ""; try { name = data[" "][0][" "][0][" "][0][" "][1][" "][0][" "][1]["C"]; } catch (error) { if (error instanceof TypeError) { console.log("name TypeError"); } } I have consid ...

AJAX is delivering a unique random hash instead of the expected text

I am in the process of developing a live notification script, and I have encountered an issue. Instead of receiving plain text from the external file, the script is returning a random hash... Here is the function responsible for fetching data from test.ph ...

Is it possible to utilize the existing class elements as an array identifier?

Can you leverage a string from an element's CSS class as an array name? I am searching for a more efficient way to store default animations that may expand gradually to encompass more options in the array. Example JavaScript (jQuery): - var col ...

Evaluating the similarity between a Guild ID and a matching string

Currently, I am in the process of creating a bot with a unique feature - a config command that enables users to customize specific functionalities within their servers. This customization is facilitated through a straightforward JSON file named config.json ...

Utilizing Regular Expressions in Express.js Routes

Is there a way to extract a specific value from my URL using Express? For example, my URL structure is as follows: host/:value.schema I need to retrieve the value from this URL. Here's an example: host/horse.schema (In this case, the value wo ...

Use the onclick event to submit a form, ensuring that it can only be submitted once

For a form, I am configuring the action and triggering submission using the onclick event of a div: <div class="action_button" onclick="document.forms['test'].action='url/to/action';document.forms['test'].submit()"> < ...

What is the best way to automatically insert data into a database at regular intervals, while ensuring that users are unable to manipulate the timing through inspect

Is there a secure way to insert 1 point into the database every x seconds without allowing users to manipulate the interval time through inspect element? var time = 1; var interval = setInterval(function() { if (time != time + 1) { ...

having difficulty implementing the blur effect in reactJS

Currently, I am working on developing a login page for my project. Below is the code snippet I have implemented for the functionality: import React, { useState, createRef } from "react"; import { Spinner } from "react-bootstrap"; import ...

Issue with JQuery's parentsUntil method when using an element as a variable not producing the desired results

I'm having trouble with a specific coding issue that can be best illustrated through examples: For example, this code snippet works as expected: $(startContainer).parents().each(function(index, parentNode) { if (parentNode.isSameNode(commonConta ...

Tips for Sending Information to the Current Page Using JQuery

I am attempting to send the form data back to the same location as the form itself. The code needs to: Trigger the click action for #submit Retrieve data from #email, #selection1, and #selection2 Hide the form #form Show the data in #email, #selection1, ...