Small bug with my contact form validation. Email validation is getting tangled with the rest of my code

Viewed 50

I've written some validation code for my contact form. While executing, the code will highlight an invalid input and display the (error) label.

While the validation is working correctly, the email input is incorrectly showing the label. Code 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>

JSFiddle here

2 Answers
Related