My contact form validation has hit a snag with a small bug. The email validation seems to be intertwining with the rest of my

I have implemented validation code for a contact form. When the code runs, it will identify any invalid input and display an error label.

Although the validation is functioning correctly, the email input is not displaying the error label as expected. See the code snippet below:

 $(".cform").on("submit" , function(e){

   var hasError = false;

    $(".inputValidation").each(function(){
      var $this = $(this);
      var $label = $("label[for='"+$(this).attr("id")+"']");
      var validateEmail = function(elementValue){
          var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
    return emailPattern.test(elementValue);
      }
      var value = $('#email').val();
      var valid = validateEmail(value);

      if($this.val() == ""){
        hasError = true;
        $this.addClass("inputError");
        $label.addClass("label_error");
        e.preventDefault();
      }if(!valid){
        $("#email").addClass("inputError");
        $label.addClass("label_error");
        e.preventDefault();
      }if($this.val() != ""){
       $this.removeClass("inputError");
       $label.removeClass("label_error");
      }else{
       return true;
     }

    });
 });
.cform {
  width: 50%;
}

.cform .inputError {
background-color: #ffffff;
  outline: 2.5px solid #900f0f;
  color: black;
}

.input_label {
display: none;
}

.label_error {
display: block;
color: #900f0f;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="cform" action="" method="post">
<label class="input_label" for="name">ERROR</label>
        <input type="text" id="name" class="inputValidation shad" name="name" value="" placeholder="Name...">
<label class="input_label" for="email">ERROR</label>
        <input type="text" id="email" class="inputValidation shad" name="email" value="" placeholder="Email...">
<label class="input_label" for="phone">ERROR</label>
        <input type="text" id="phone" class="inputValidation shad" name="phone" value="" placeholder="Contact Number...">
<label class="input_label" for="message">ERROR</label>
        <textarea name="message" id="message" class="inputValidation shad" placeholder="Type your message here..."></textarea>
        <input type="submit" class="" name="sumbit" value="send">
      </form>

Link to JSFiddle

Answer №1

It appears that the issue arose from correctly adding the error label class when the email was invalid, but there was a problem with the if statement at the end. This if statement only checked for whether the input had any value, so even if the email was not valid, the label was still removed.

An easy fix is to separate the if statements for better validation.

$(".cform").on("submit", function(e) {
  var hasError = false;

  $(".inputValidation").each(function() {
    var $this = $(this);
    var $label = $("label[for='"+$(this).attr("id")+"']");
    var validateEmail = function(elementValue) {
      var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
      return emailPattern.test(elementValue);
    }
    
    var value = $('#email').val();
    var valid = validateEmail(value);

    if ($this.val() == "") {
      hasError = true;
      $this.addClass("inputError");
      $label.addClass("label_error");
      e.preventDefault();
    } else {
      $this.removeClass("inputError");
      $label.removeClass("label_error");
    }

    if (!valid) {
      $("#email").addClass("inputError");
      $label.addClass("label_error");
      e.preventDefault();
    } else {
      $this.removeClass("inputError");
      $label.removeClass("label_error");
    }
  });
});

Answer №2

There was an issue with the sequence of validations. The error generated by the email field was being overridden by a non-null validation.

 $(".cform").on("submit" , function(e){

   var hasError = false;

    $(".inputValidation").each(function(){
      var $this = $(this);
      var $label = $("label[for='"+$(this).attr("id")+"']");
      var validateEmail = function(elementValue){
          var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
    return emailPattern.test(elementValue);
      }
      var value = $('#email').val();
      var valid = validateEmail(value);
   //validation for mandatory start
      if($this.val() == ""){
        hasError = true;
        $this.addClass("inputError");
        $label.addClass("label_error");
        e.preventDefault();
      }else{
       $this.removeClass("inputError");
       $label.removeClass("label_error");
        return true;
      }
      //validation for mandatory end

      //validation for email start
      if(!valid){
        $("#email").addClass("inputError");
        $label.addClass("label_error");
        e.preventDefault();
      }
      else{
       $this.removeClass("inputError");
       $label.removeClass("label_error");
      }
     //validation for email end
      
    });
 });

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

Steps to create a persistent bottom modal with scrollable content

I'm currently using Bootstrap 4.6 within my Angular application. I have implemented a modal that expands to full-screen on mobile devices, and now I want to add a fixed footer with scrolling body content. I've attempted to adjust the height of t ...

JavaScript Oddity - Array Increment Trick

What is the reason behind ++[[]][0] == 1 While trying to do ++[] leads to an error? Shouldn't they produce the same result? My understanding is that the first example performs an index-read on the array, resulting in an array within an array. The ...

How to Generate HTML Reports Using JBoss?

Is there a convenient and efficient way to generate .html reports for JBoss applications that is not time-consuming? I have a database containing entities that I need to display in multiple tables. The report should include links to navigate between secti ...

How can a node be added between two nodes based on an attribute condition?

Is there a jQuery function, or perhaps another library function, that allows for the insertion of a node (div) between two other nodes (divs) based on its attribute? For instance: Assume I have the following HTML code: <div value=111/> <div val ...

Switching the chosen option with jQuery

Here is the html code I am using: <select name="one_day_per_month" id="one_day_per_month" style="width: 200px"> <option value="false" selected>No</option> <option value="true">Yes</option> </select> The HTML page i ...

ERROR: The data has reached its end prematurely (data length = 0, requested index = 4). Could this be a corrupted zip file?

Currently, I am developing a WhatsApp bot and storing the chat data in an Excel file using exceljs for further processing. In order to handle responses efficiently, I am utilizing promises to resolve them. Below is the function I have created to read the c ...

Can you explain the purpose of using "link href="#""?

While browsing through the source code of a website, I came across this interesting snippet. <link href="#" id="colour-scheme" rel="stylesheet"> I'm curious, what exactly does this code snippet do? ...

What methods with JavaScript, Ajax, or jQuery can I apply to populate the student details?

For completing the StudentID section, please fill out the form data.cfm with the first name, last name, and Middle Name. <script language="Javascript"> $(function() { $( '#effective_date' ).datepicker(); jQuery.validator.addMetho ...

Exploring the Syntax of React

As I am still fairly new to react and have a basic understanding of Javascript. Following a tutorial, everything was clear until the instructor moved forward. Now, when I go back over the material, I find myself struggling to grasp this concept. render() ...

Display various elements depending on the size of the screen within Next.js

My goal is to display a component differently depending on whether the screen width is less than 768p or not. If the width is under 768p, I want to show the hamburger menu. Otherwise, I want to display the full menu. This is the code snippet I am using. ...

Using the CSS trick of First-of-type and Last-of-type can result in shortened rounded edges when viewed in IE11

When using the radio+label trick to style radio buttons, a peculiar issue arises in Internet Explorer 11 (IE11). The first and last buttons in each set appear to have their bottom parts cut off or shortened, depending on the background displayed. Removing ...

What is the method for running a powershell script within protractor testing?

I am attempting to run a powershell script within my protractor test. Protractor spec.ts it("Executing Powershell Script", async () => { browser.get('http://mywebsite.com') var spawn = require('child_process').spawn; ...

Is it feasible to maintain a persistent login session in Firebase without utilizing the firebase-admin package through the use of session cookies?

Currently, I am integrating Firebase into my next.js application for user login functionality. The issue I am facing is that users are getting logged out every time they switch paths within the site. Even though their session cookie has not expired, if the ...

When a page is changed, the Vue.js Active Menu color remains enabled

Check out my website at . I want to customize the navigation bar so that only the active page's navbar li is colored in red. <div class="navigation-items"> <ul class="nav-list"> <li class="nav-item"><nuxt-link to="/en" ...

PHP encoding a multidimensional associative array into JSON and passing it to JavaScript

Greetings, initially my array had this structure: PHP $results = array( "banana" => $bananavalue, "apple" => $applevalue, ); echo json_encode($results); JS var fruits = []; $.ajax({ type: "POST", url: "actions/MYphp.php", data: Pass ...

Retrieve only the radio buttons that are currently visible on a form using jQuery

I have a form with numerous visible and hidden radio buttons. I am attempting to isolate only the visible radio buttons for manipulation using the code below, but it's not functioning as expected. Can someone offer assistance? $('#submitbutton&a ...

Display the result obtained from the AJAX request

Here is the AJAX code that I need to use in order to display a value on an HTML page. var val = $.ajax({ type: "post", url: "count.jsp", data: "", cache: false, success: function(str) ...

Verifying CSS updates with Capybara detection

I'm in the process of developing a web application that dynamically changes its CSS styles based on user input. Everything is working smoothly, but I'm facing an issue with my automated tests not confirming whether the CSS updates are actually ta ...

What is the best way to randomly assign colors to my website links?

I'm trying to figure out why my code isn't functioning properly. Is there a mistake I'm not seeing? window.onload = function randomizeColor() { var links = document.getElementsByTagName('a'); var colors = new Array("green" ...

What steps do I need to take in order to show the present value using a range input?

Hey there! I'm working on a code in HTML that includes an input of type range. Here's what it looks like: This is my input: <input type="range" min="1" max="100" value="50" class="slider" id="myRange"> Unfortunately, I'm unable to s ...