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>