What is the best way to display an error message for an invalid input using JavaScript?

I am struggling to implement error messages for my form inputs using JavaScript. My attempts so far have not been successful and I need guidance on the correct approach.

I want to show an error message and prevent the form from being submitted if any errors are present.

<form novalidate>
      <label for="password">
         <input type="password" name="password" id="password" placeholder="Password*" required minlength="8" />
         <span id='pwmessage'></span>
      </label>
      <label for="confirmpassword">
        <input type="password" name="confirm_password" id="confirm_password" placeholder=" Confirm password*" required minlength="8" />
        <span id='cpwmessage'></span>
      </label>
      <button>Submit</button>
  </form>

Answer №1

Give this method a shot! In this scenario, the submission will not go through if either the password or confirm password fields are left empty, or if the confirm password does not match the initial password.

function checkEmpty() {
    if (document.getElementById("password").value == "") {
        document.getElementById("pwmessage").innerHTML = "Please enter at least one character in the password field";
        return false;
    }
    if (document.getElementById("confirm_password").value != document.getElementById("password").value) {
        document.getElementById("cpwmessage").innerHTML = "Kindly verify your password and try again";
        return false;
    };
}
<form novalidate action='process.php' method='get'>
    <label for="password">
       <input type="password" name="password" id="password" placeholder="Password*" required minlength="8" /><br>
       <span id='pwmessage'></span><br>
    </label>
    <label for="confirmpassword">
      <input type="password" name="confirm_password" id="confirm_password" placeholder=" Confirm password*" required minlength="8" /><br>
      <span id='cpwmessage'></span><br>
    </label>
    <input type="submit" value="submit" onClick="return checkEmpty()" />
</form>

Appreciate it and warm regards!

Answer №2

Discover numerous form validation tutorials available to spark your creativity.

This particular version utilizes data attributes and is highly scalable without requiring additional javascript. While more work may be necessary for additional input types, this code is a great starting point.

//Implement validation on blur for each element
document.querySelectorAll("[data-customvalidate] input").forEach(function(element) {
  element.addEventListener("blur", function() {
    validateField(this)
  });
});


//Set up form validation
document.querySelectorAll("[data-customvalidate").forEach(function(element) {
  element.addEventListener("submit", function(event) {
    let isNotValid = false;
    //Iterate through each input element
    this.querySelectorAll("input").forEach(function(input) {
      //Validate the input and set the isNotValid flag
      if (validateField(input) && !isNotValid) {
        isNotValid = true;
      }
    });

    //Prevent form submission if not valid
    if (isNotValid) {    
      event.preventDefault();
    }
  });
});


//Main Validation Function
function validateField(field) {
  let attributes = field.getAttributeNames();
  let parent = field.parentNode
  let errorField = parent.querySelector(".formError");

  let isError = false;
  //Required Validation
  if (attributes.includes("required") && field.value === "") {
    errorField.textContent = `The ${field.dataset.errorfieldname} field is required`;
    isError = true;
    //Min Length Validation
  } else if (attributes.includes("minlength") && (field.value.length < field.getAttribute("minlength"))) {
    errorField.textContent = `The minimum length for ${field.dataset.errorfieldname} field is ${field.getAttribute("minlength")} characters`;
    isError = true;
    //Match Validation
  } else if (attributes.includes("data-mustmatch")) {
    let elementToMatch = document.getElementById(field.dataset.mustmatch);
    if (elementToMatch.value !== field.value) {
      errorField.textContent = `The ${elementToMatch.dataset.errorfieldname} and ${field.dataset.errorfieldname} do not match`;
      isError = true;
    }
  }

  parent.classList.toggle("error", isError);
  return isError;
}
label {
  display: block;
}

label:not(.error)>.formError {
  display: none;
}

label>.formError {
  color: red;
  font-weight: bold;
  padding-left: 1em;
}
<form novalidate data-customvalidate>
  <label for="password">
         <input type="password" name="password" id="password" placeholder="Password*" required minlength="8" data-errorfieldname="Password" />
         <span class="formError"></span>
      </label>
  <label for="confirmpassword">
        <input type="password" name="confirm_password" id="confirm_password" placeholder=" Confirm password*" required minlength="8" data-errorfieldname="Confirm Password" data-mustmatch="password" data-mustmatcherror= "Password and Confirm Password do not match" />
        <span class="formError"></span>
      </label>
  <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

Finding the distance between two points in JavaScript requires a simple formula

Here is a code snippet that generates two TRACER points and displays them on a map, as well as shows the union between the two points. <?php $latitudInicio = $_GET['latitudInicio']; $longitudInicio = $_GET['longitudInicio']; $latit ...

Challenge with Making Backgrounds Responsive on Android Chrome

I’m facing an issue with the responsive background on Android Chrome. It displays correctly on PC browsers like Safari, Firefox, and Opera, as well as in Firefox on Android. However, I am encountering a problem with Chrome on Android where it doesn’t a ...

Performing mathematical calculations using javascript

In my project, I'm utilizing HTML, CSS, and JavaScript to achieve the following: Dropdown menu for Category (Coffee Appliance) Dropdown menu for Product (Keurig Coffee Maker) Wattage: 1500kWh (auto-filled from Local Storage) Daily Energy Con ...

How do I assign a variable to a session in Express.js?

I am currently working on a login form that prompts users to enter their username, password, and company name. The company name corresponds to the database name, so I need to store this information in the session during the login post request. In my opini ...

CSS: Ensuring the width is adjusted to the content or wrapper that is wider

I am facing an issue with mouse-over highlighting on a set of list items. Below is the HTML structure I am working with: <div id="wrapper"> <div id="box"> <div class="item">Lorem ipsum dolor sit amet, sit nonumy utamur ponderum ex& ...

Returning a 404 Error stating "Invalid request to /api/users/register."

Encountering an issue with proxy connection - unable to determine the root cause despite verifying all routes. Not able to successfully register the user and store data in MongoDB. Seeking suggestions for resolution. Thank you. Attempting to send user reg ...

Contrasting Template Helper and Template Variable in Meteor.js

What sets apart the use of a Template Helper from a Template Variable (if that's not the right term)? How do you determine when to utilize each one? In the following example, both Template.apple.price function and the quantity function in Template.ap ...

Ways to update a component upon becoming visible in Angular

Within my Angular 4.3.0 project, the header, left panel, and right panels are initially hidden on the login page until a successful login occurs. However, once they become visible, the data is not pre-loaded properly causing errors due to the ngOnInit meth ...

Parent element unable to trigger event due to interference from child elements

Within my HTML document, there is a parent <span> element that contains nested <em> elements. This <span> is styled with a specified width and display:block property using CSS. Despite a jQuery trigger event being successfully fired on t ...

Utilize the browser's scroll bar to control an infinite scroll feature within the UI grid

In my current project, I am utilizing a framework built on Angular.js and incorporating the UI-Grid infinite scroll feature. However, I am looking to have the infinite scroll functionality triggered by the browser's scroll bar rather than the grid&apo ...

Understanding the lockfile: deciphering the significance of each line in the yarn.lock file

I'm curious about the meaning of each line in this file. I encountered issues with packages due to dependencies in my project. After upgrading nuxt from version 1x to 2x, all tests started failing. After spending hours searching online, I discovered ...

Turn off the ability to click on images, but allow users to access the right

https://i.stack.imgur.com/jriaP.png Example image sourced from reddit.com Illustration represents the desired effect using CSS and possibly JS. In essence: I aim to make an image on a website unclickable to its imageURL There should be a context menu ...

Button will be disabled unless a value is selected in the dropdown menu

I am currently dealing with a code issue where the button is disabled on page load when the dropdown value is empty. However, even after selecting a value from the populated database dropdown, the button remains disabled. Jquery: <script> $(doc ...

Creating a div with a fixed size in Tailwind CSS: A beginner's guide

I received some initial code from a tutorial and I've been having trouble setting the correct size. Despite searching through documentation for solutions, it seems like there's a fundamental aspect that I'm overlooking. The main issue is tha ...

Connecting a Date object by using :value and @input within a VueJS component

Successfully linking a date form input with a date object using :value and @input instead of v-model as outlined in this method has been a great ongoing experience. It allows for displaying and modifying the date in the form input, as well as saving the up ...

Passing a value from a prop to a click event that is dynamically created within an SVG Vue.js

Currently, I am in the process of developing a map component using a JSON array and implementing a click event handler for each item. The objective is to toggle the CSS style to color the item when clicked, which is functioning as expected. However, my goa ...

Using WebRTC on a shared hosting environment (with SSH access) without the need for nodejs, ideally implemented in PHP

As I was exploring ways to integrate webRTC into a website that I am creating on shared hosting, I stumbled upon this GitHub repository by nielsbaloe. It has been incredibly helpful in establishing a basic connection. This particular code snippet appears ...

Suggestions for autocomplete in a textarea within an HTML element

<!DOCTYPE html> <html> <head> <base href="http://demos.telerik.com/kendo-ui/autocomplete/index"> <style>html { font-size: 14px; font-family: Arial, Helvetica, sans-serif; }</style> <title></title> ...

Is it possible to stack navbar items in CSS?

I'm facing an issue with my navbar menu items overlapping on top of each other. https://i.sstatic.net/dEEpx.png What could be the reason behind this? Codepen Link: https://codepen.io/ogonzales/pen/mdeNNLB Code Snippet: <nav class="navbar navb ...

Is there a way to connect CSS files from a different directory?

I'm currently in the process of developing a website and I encountered an issue with linking my CSS file, which is stored in a different folder. I originally had it in the same directory as my HTML code, but now I need to figure out how to link it pro ...