Having troubles with my email validation code. I keep on getting the error that my function is not defined. i have made a javascript file for the java code and then i used the o
Put your javascript in <script>
tags.
Also rename your variable name email
since your textbox is using it already.
<input type="text" id="email" name="email" onchange="check();" />
<script type="text/javascript">
function check() {
var email_x = document.getElementById("email").value;
filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (filter.test(email.value)) {
document.getElementById("email").style.border = "3px solid green";
return true;
} else {
document.getElementById("email").style.border = "3px solid red";
return false;
}
}
</script>
Here is the code for html input field and button field
<input input type="text" name="txtEmailId" id="txtEmailId" />
<input type="submit" class="button" value="Suscribe" name="Suscribe"
onclick="javascript:ShowAlert()" />
Now add the below function to the header of your page
<script type="text/javascript">
function ShowAlert() {
var email = document.getElementById('txtEmailId');
var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (!filter.test(email.value)) {
alert('Please provide a valid email address');
email.focus;
return false;
}
else {
alert("Thanks for your intrest in us, Now you
will be able to receive monthly updates from us.");
document.getElementById('txtEmailId').value = "";
}
}
</script>
Here you can find the article on this Email Validation in JavaScript
If you are specific about the domains , you may use this code for email validation so as to prevent anonymous email domains.
(^([a-zA-Z]{1,20}[-_.]{0,1}[a-zA-Z0-9]{1,20})(\@gmail\.com|\@yahoo\.com|\@hotmail\.com)$)
You may add additional domains too.
Email validation is not always as simple as your regular expression. Have you looked at:
Validate email address in JavaScript?
A better option would be to use Verimail.js. It's a simple script that takes care of it for you. With Verimail.js you could just do:
var email = "cool@fabeook.cmo";
var verimail = new Comfirm.AlphaMail.Verimail();
verimail.verify(email, function(status, message, suggestion){
if(status < 0){
// Incorrect syntax!
}else{
// Syntax looks great!
}
});
The above example will hit the line 'Incorrect syntax!' because of the invalid TLD 'cmo'. Besides this, it will also give a suggestion that you can return to your user, in this case, the suggestion variable will contain 'cool@facebook.com' since 'fabeook.cmo' looks a lot like 'facebook.com'.
Hope this helps!