Mistakes in validating email form

I'm having some difficulties creating a basic contact form.

I'm following the guidelines outlined in and the initial step involves using JavaScript to highlight the input box with a red border when invalid input is entered.

Unfortunately, the code I'm using below doesn't seem to be working as expected.

const inputs = document.querySelectorAll("input, select, textarea");

inputs.forEach(input => {
  input.addEventListener(
    "invalid",
    event => {
      input.classList.add("error");
    },
    false
  );
});
/*Email Validation*/


input.invalid {
  border-color: red;
}
          <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.3/css/bootstrap.min.css" integrity="sha384-Zug+QiDoJOrZ5t4lssLdxGhVrurbmBWopoEl+M6BdEfwnCJZtKxi1KgxUyJq13dy" crossorigin="anonymous">

  <h1 class="text-center font-bold mt-5 pt-2 mb-3">
          <em>Contact us</em>
      </h1>

      <!-- contact-->
         <section id="contact" style="background-color: #fff;" class="text-page">
           <div class="container">
             <div class="row">
               <div class="col-md-12">
                 <h2 class="heading">Contact</h2>
                 <div class="row">
                   <div class="col-md-6">
                     <form id="contact-form" method="post" action="#" class="contact-form">
                       <div class="controls">
                         <div class="row">
                           <div class="col-sm-6">
                             <div class="form-group">
                               <label for="name">Your firstname *</label>
                               <input type="text" name="name" placeholder="Enter your firstname" required="required" class="form-control">
                             </div>
                           </div>
                           <div class="col-sm-6">
                             <div class="form-group">
                               <label for="surname">Your lastname *</label>
                               <input type="text" name="surname" placeholder="Enter your  lastname" required="required" class="form-control">
                             </div>
                           </div>
                         </div>
                         <div class="form-group">
                           <label for="surname">Your email *</label>
                           <input type="email" name="email" placeholder="Enter your  email" required="required" class="form-control">
                         </div>
                         <div class="form-group">
                           <label for="surname">Your message for us *</label>
                           <textarea rows="4" name="message" placeholder="Enter your message" required="required" class="form-control"></textarea>
                         </div>
                         <div class="text-center">
                           <input type="submit" name="name" value="Send message" class="btn btn-primary btn-block">
                         </div>
                       </div>
                     </form>
                   </div>
                   <div class="col-md-6">
                     
                     <p class="social"><a href="#" title="" class="facebook"><i class="fa fa-facebook"></i></a><a href="#" title="" class="twitter"><i class="fa fa-twitter"></i></a><a href="#" title="" class="gplus"><i class="fa fa-google-plus"></i></a><a href="#" title="" class="instagram"><i class="fa fa-instagram"></i></a><a href="#" title="" class="email"><i class="fa fa-envelope"></i></a></p>
                   </div>
                 </div>
               </div>
             </div>
           </div>
         </section>

Answer №1

There is a mistake in the code provided, make sure to update the class name from input.invalid to input.error

/*Email Validation*/


input.invalid {
 border-color: red;
}

to

input.error{
  border-color: red;
}

Answer №2

Utilize vanilla JavaScript's .checkCustomValidity method. You can implement something similar to the following code snippet within a .keyup event listener attached to the entire form for an effective validation. Please note that this code is a manual implementation and may require adjustments.

Subsequently, you can manage the state of your "Submit" button by enabling or disabling it based on the validation status.

function formValidation(formId){
var isValid = true;
var formInputs = document.getElementById(fodmId).querySelectorAll("input");
    for (var i = 0; i < formInputs.length; i++) {
        // Check if the input is visible and not disabled
        if(formInputs[i].offsetHeight > 0 && !formInputs[i].attribute("disabled","disabled")){
            if(!formInputs[i].checkValidity()){
                isValid = false;
            }
        }
    }
    return isValid;
}

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

Having an issue with deleting a table row using jQuery when the button is clicked

I am facing an issue where clicking on a button does not delete the table row despite both the tr id and button id having the same value. Can someone please guide me on what might be going wrong? <tr id="<?php echo $result->id;?>"> <t ...

What is the best way to update the state while invoking a component?

Just starting out with react and already hitting a roadblock. I've created an Article Topper component that features a logo, title, and share buttons, which is repeated throughout the site above each article. The issue I'm facing is updating the ...

Is your Phonegap and Jquery app experiencing delays in script loading?

I recently developed a phonegap + JQM application and encountered an issue with the loading time of external JavaScript files. To elaborate, when the app starts, the initial file that appears is loader.html. In this file, I have included several JS files ...

What are the steps to refreshing a table using AJAX?

Struggling to update a table from my database, I have been following a PHP guide but can't get it to work. In a separate file, the data is retrieved and displayed in a table. I am attempting to use JavaScript to refresh this file. This code snippet ...

Obtain the precise X and Y coordinates of a <li> element regardless of where the mouse is clicked using Typescript

I'm stuck and could really use some assistance! Hey there, I have a simple question but I seem to be missing a crucial element. Here's my fiddle where I can detect the clicked item but that's as far as I've gotten: http://jsfiddle.ne ...

When handling cross-domain Jquery Ajax requests, the error function may unexpectedly return a success status

While attempting a cross domain GET request using jQuery AJAX, I am encountering a situation where the error function returns success as the status. The data I am expecting to be returned from the get service is: document.write("<div class=\"displ ...

Tips on adding several elements to an array depending on the selected value from various checkboxes?

I am working on a project where I need to populate an array based on selected checkboxes. Let's assume we have 3 arrays containing strings: const fruits = ["Apple", "Banana", "Orange", "Grapes"]; const vegetable ...

Kendo UI Scheduler: The system encountered an overflow while converting to a date and time format

Working on a project using .NET MVC and the Kendo UI Scheduler, an open-source tool. The goal is to save, read, update, and delete events from the scheduler into the database using JavaScript. Encountering some challenges in the process - when attempting ...

What can be done to resolve the issue of 'this.state.*.map' not being a function

I am encountering an issue while trying to export a single row from my component import React, {Component} from 'react'; class TableRow extends Component { state = { row: [] }; componentWillMount() { this.setState({row: this.props.chil ...

Decoding the values in an input field

Can anyone help me with identifying links, numbers, and text in WhatsApp and other app input boxes? I also want to be able to preview the page attached to a link and style these elements separately from other text. I am currently working on a project whe ...

Tips for transmitting one or multiple data using jquery.ajax

I found this code on stackoverflow and it is working well for uploading multiple files. However, I am facing an issue where I cannot send additional parameters along with the file upload. Despite trying various methods, I have been unsuccessful in sending ...

Record the marker's location only once following the completion of its dragging action

Is there a way to make the console log for getPosition only happen when the marker is stopped being dragged, rather than every 0.1 seconds while it's being dragged? Similar to how .getRadius() works - it logs the radius change just once. https://i.ss ...

How can I position text below a ticked checkbox?

Having an issue with my HTML and jQuery code. Everything is working fine, but when I click on a checkbox, the text "FINISHED" appears below all checkboxes instead of just the one I clicked on. This is my html code: $('.label__checkbox').cli ...

What are the key differences between using role and class selectors in HTML 5 and CSS3 to create two sidebars with three

My decision to eliminate all ids from my CSS and transition to HTML 5 has led me to question the use of roles in markup. In the past, IDs were used to style sidebars individually within a single selector for both. Here is an example: <div id="sidebar" ...

Using ajax to submit a form in CodeIgniter and displaying the returned data in a table view

When I submit a form on the view page, I want the form data to be saved in a database table and displayed without refreshing the page. Below is my view code: <div class="col-md-12"> <div class="row"> <div> <table class="table table-s ...

Passing HTML element values to Python in Odoo 10: A complete guide

I am working on an Odoo module that includes an Html <select> tag. I need to pass the value of the <option> (within the select tag) to a Python model so that I can perform certain actions based on this value. Can anyone provide guidance on how ...

Directives for Nested Elements in AngularJS

I am currently working on creating two custom elements: <accordion> and <accordion-group-active>. .directive('accordion', function () { return { restrict: 'E', replace: true, transclude: true, ...

The rendering of code is often disrupted when utilizing the keyword const

I've been working my way through the Angular2 tutorial called Tour of Heroes and everything has been going smoothly up until this point. At the link above, I've encountered a problem. The code on the left is what the tutorial recommends, but fo ...

Regular Expression - Invalid character detected in output

I'm currently in the process of developing a function to verify if a field is deemed acceptable based on a specific character set. In case it doesn't meet the criteria, I aim to determine and communicate which characters are not permitted. While ...

Utilize the jQuery ajax post method within each loop to handle asynchronous requests, ensuring that the

I am currently working on a jQuery ajax function that is embedded within an each function as it needs to be executed for each post on the website. $('.post .button').each(function() { $(this).click(function() { $.ajax({ url: 'action ...