I currently have a form that includes an option element and an email field at the top.
<form class="form-versenden" action="mainVersendet.php" method="post" name="send">
<div class="form-group">
<h4>Please enter the following data</h4>
<div class="form-group">
<label for="versandart">Shipping method</label>
<select class="form-control" id="versandart" name="versandart" autofocus>
<option value="both">Email and Print</option>
<option value="onlyEmail">Email Only</option>
<option value="onlyPrint">Print Only</option>
</select>
</div>
<div class="form-group">
<label for="email">Email</label>
<input type="email" class="form-control" id="email" placeholder="email" name="email">
</div>
<button class="btn" type="submit">Send</button>
</div>
</form>
Depending on the user's choice, I need to validate whether an email address is entered in the 'both' and 'onlyEmail' cases. Since the email field is not required in all 3 cases, I cannot solely rely on the HTML required attribute. Therefore, I attempted to validate it upon submission as follows:
document.querySelector('form[name="send"]').addEventListener("submit", validateFields);
function validateFields(){
var versandart = document.getElementById("versandart");
var email = document.getElementById("email");
if (versandart.value == 'both' || versandart.value == 'onlyEmail'){
if(email.value == ''){
email.setCustomValidity('Email must be provided');
return false;
}else if(CHECK HERE if Mail is not correct){
email.setCustomValidity('Email format is not correct');
return false;
}else{
//in this case email is not empty and is correct
return true;
}
}
}
However, this approach is ineffective as it overrides the standard HTML validation for a valid email address. So I need to recheck the email validation at the point where it says 'CHECK HERE if Mail is not correct'.
Is this the appropriate method to handle this issue or should I consider adding an onchange listener to the versandart field and dynamically adding the required attribute to the email field based on the selected value?