I have seen similar questions but they were not asked the same way I want to ask my question.
How can I use javascript to make sure that the email a user provides matches with the email that I want them to provide before the form gets submitted after the user hits the submit button.
Elaboration:
The correct email address is [email protected].
My form input placeholder shows [email protected] as a hint.
If the user inputs any email that does not match with [email protected] I want them to get an error message and the form should not be submitted.
How can I do this with javascript?
See my code below.
<form action='' method='POST' enctype="multipart/form-data">
<div class='item'>
<p><b><span style="color: red;">Email Address</span></b><span class='required'>*</span></p>
<input type="email" name="email" placeholder="ba******o@***.com" required=''/>
</div>
<div class='question'>
<center><p>Privacy Policy<span class='required'>*</span></p></center>
<div class='question-answer checkbox-item'>
<div>
<center><label class='check' for='check_1'><span>By submitting this form you agree to the terms of service <a href='https://www.google.com/p/privacy-policy.html' target="_blank">privacy policy.</a></span></label></center>
</div>
</div>
</div>
<div class='btn-block'>
<center> <button href='/' type='submit' id="submitForm">Submit</button></center>
</div></form>
CodePudding user response:
If I'm correct, you need to add and change a few things so it would work.
First, add an 'id' attribute to the email input field like this (so we can link the form to the javascript code later on):
input type="email" name="email" placeholder="ba******o@***.com" required='' id="email"/>
Then, add the following script at the beginning of the page (between the and the tags). This script compares the entered email and shows a message if they are not matching.
<script type="text/javascript">
function check_email()
{
var email = document.getElementById("email").value;
if(email.localeCompare("[email protected]")) {
alert("ERROR. Email does not match.");
return false;
}
return true;
}
Finally, add the 'onsubmit' attribute to the tag like this (if the function that checks the email returns false, then the form won't be sent):
<form action='' method='POST' enctype="multipart/form-data" onsubmit="return check_email();">
I hope this works for you :)