I am new to JavaScript and need to verify that the emails match in two input boxes. It only needs to verify that they match, not that they are correctly formatted emails. What I have now does alert when they don’t match, but also alerts the same thing when they do match. Can anyone help?
function verifyEmail() {
let email1 = document.getElementById("email")
let email2 = document.getElementById("emailConf")
if (email1 == email2) {
return true;
}
else {
alert("Emails do not match.");
}
}
<form action="mailto: [email protected]" method:="post" enctype="text/plain">
<label>First Name:</label>
<input type="text" name="firstName" placeholder="First Name"><br>
<label>Last Name:</label>
<input type="text" name="lastName" placeholder="Last Name"><br>
<label>Email:</label>
<input type="email" id="email" name="email" placeholder="Email"><br>
<label>Confirm Email:</label>
<input type="email" id="emailConf" name="emailConf" placeholder="Confirm Email"> <br>
<label>Message:</label><br>
<textarea name="yourMessage" cols="30" rows="10" placeholder="Type your message here."> </textarea><br>
<br> <button onclick="verifyEmail()";>Submit</button>
</form>
I tried numerous solutions but none were successful.
2
Answers
You’re currently comparing the input elements, so they’ll always be different.
Try changing
if (email1 == email2) {
toif (email1.value == email2.value) {
This will compare the values in the input elements, rather than the elements themselves.
In your function, you need to replace
with
and everything should work correctly.