I am having a really hard time with a form validation and would appreciate some help. Essentially I have a form with various required fields, to include inputs, select, and textarea. One of the form fields is for an email address that I want to validate.
The problem I have is that I loop through the form elements using the querySelectorALL and check to see if a field is both required AND not empty. The problem I have is integrating a second validation for the email field. In the main loop, it may show as required and NOT empty, but could contain an invalid email value.
So I thought to create a second conditional in the for loop, to check if the name of the item is "Email", and if it was, check it for validity.
What I find is that submitting the form with the placeholder makes the field's placeholder text red. If I then put in an invalid email address, the field turns black, but if you look at my conditional, if it is an invalid email the value should stay red, but it does not.
I hope this is making sense. I have been at this for hours and really struggling.
function validateAppt() {
var returnVal = true;
var divElem = document.getElementById("appointmentform");
var inputElements = divElem.querySelectorAll("input, select, textarea");
inputElements.forEach(a => a.style.color = "black");
inputElements.forEach(a => a.style.borderColor = "black");
for (let i = 0; i < inputElements.length; i++) {
if (inputElements[i].required && inputElements[i].value == "") {
inputElements[i].style.borderColor = "red";
if (inputElements[i].type != 'select-one') {
inputElements[i].style.setProperty("--c", "red");
} else {
inputElements[i].style.color = "red";
}
returnVal = false;
}
if (inputElements[i].name == "Email") {
if (!validateEmail(inputElements[i].value)) {
inputElements[i].style.setProperty("--c", "red");
inputElements[i].style.color = "red";
console.log("InValid Email");
} else {
inputElements[i].style.color = "black";
console.log("Valid Email");
}
}
}
if (!returnVal) {
$("#appointment_introduction").css('color', 'red').text('Please complete required form fields.');
$('html, body').animate({
scrollTop: $('#appointment_introduction').offset().top - 200
}, 2000);
return false;
} else {
return true;
}
}
function validateEmail(email) {
var re = /^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,10}|[0-9]{1,3})(\]?)$/;
return re.test(email);
}