Validating e-mail address - javascript

I am trying to validate an e-mail address using javascript. The problem is the if statements aren't executing correctly. If I delete the 'else statement' the code runs correnctly and the page does not load with errors. If I include the 'else statement' the else statement never executes and the status bar says that the page loads with errors. I was wondering if anyone can find any errors that I am unable to pick up?
<h4>Example 4:</h4>
<div style="border:3px dashed #aaa; width:200px;">
<div id="text">e-mail: <input id="email" onblur="verifyEmail()"/></div>
<div id="verification" > </div>
</div>
<script type="text/javascript">
function verifyEmail(){
var email = document.getElementById("email").value;
var atPos=0;
var dotPos=0;
atPos = email.indexOf("#");
dotPos = email.lastIndexOf(".");
if(atPos<=3 || dotPos<atPos+2 || dotPos+2>=email.length){
document.getElementById("verification").innerHTML = "Invalid E-mail Address";
}else{
document.getElementById("verification").innerHTML = "Valid";
}
}
</script>

<script language="javascript">
function checkEmail() {
var email = document.getElementById('emailaddress');
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;
}
}
</script>
Read more: http://www.marketingtechblog.com/javascript-regex-emailaddress/#ixzz1wqetPJQQ

try this
function validateEmail(email) {
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\
".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA
-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
Demo : Here is the demo
OR a more simpler way is
function validateEmail(email)
{
var re = /\S+#\S+\.\S+/;
return re.test(email);
}
if you are using HTML5 try <input type="email"... please note. this one works if the input is in a form tag with a submit button and isn't handled by JS
<input type="email" placeholder="me#example.com">

Related

how to validate email in javascript

I am working on a mvc 5 project .in contact us page I want user to send admin his / her emaiul address .so I want to validate email in javascript on that page .I wrote some code that does not work properly. I want you to help me plesae.
<script language="javascript">
function f1() {
var inputText = document.getElementById("email").value;
var mailformat = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (inputText.value.match(mailformat)) {
document.form1.text1.focus();
}
else {
alert("You have entered an invalid email address!");
document.form1.text1.focus();
event.preventDefault();
}
}
</script>
<form name="form" action="#" onSubmit="return f1()" method="POST">
<input type="email">
</form>
<script>
function f1(){
var email = document.forms["form"]["Email"].value;
var regex = /^([0-9a-zA-Z]([-_\\.]*[0-9a-zA-Z]+)*)#([0-9a-zA-Z]([-_\\.]*[0-9a-zA-Z]+)*)[\\.]([a-zA-Z]{2,9})$/;
if(!regex.test(email)){
alert("You have entered an invalid email address!");
return false;
}
}
</script>
You don't want inputText.value only inputText like this
<input type="text" id="email" />
<input type="submit" onClick="f1()"/>
<script language="javascript">
function f1() {
console.log(document.getElementById("email").value);
var inputText = document.getElementById("email").value;
console.log(inputText)
var mailformat = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (inputText.match(mailformat)) { // <<<<<<< here
//document.form1.text1.focus();
alert("correct")
}
else {
alert("You have entered an invalid email address!");
document.form1.text1.focus();
event.preventDefault();
}
}
</script>
A basic HTML and JS working code for validating email with JS is given here for u-
function validateForm()
{
var x = document.forms["myForm"]["email"].value;
var atpos = x.indexOf("#");
var dotpos = x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
{
alert("Not a valid e-mail address");
return false;
}
else
{
alert("Valid e-mail address");
return true;
}
}
<form name="myForm" action="demo_form.asp" onsubmit="return validateForm();" method="post">
Email: <input type="text" name="email">
<input type="submit" value="Submit">
</form>
Think, u have your answer :)
function validateEmail(email) {
var re = ([\w-+]+(?:\.[\w-+]+)*#(?:[\w-]+\.)+[a-zA-Z]{2,7});
return re.test(email);
}

validate email javascript: show cross when email incorrect/show tick when email correct?

Im having a problem with my email validation script, at the moment my script validates the text in the email text box once the user clicks out of it, displaying a cross if the email is not valid and then a tick if the email is valid, the problem i get is if the user types in a valid email and then for whatever reason if they then go back and type an ivalid email i get both the cross and the tick showing up on top of each other at once.
Does anyone know how i can ammend this to only have the cross showing when email is invalid and only show the tick when email is valid.
Here is my Code :
<script>
function validateEmail(emailField){
var reg = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
if (reg.test(emailField.value) == false)
{
document.getElementById("emailCross").style.display='block';
return false;
}
document.getElementById("emailCross").style.display='none';
document.getElementById("emailTick").style.display='block';
return true;
}
</script>
html:
<input type="text" id="field_email" name="email" onfocus="document.getElementById('field_email').style.background='#ffffff';" onblur="validateEmail(this);" />
<div id="emailCross"></div><div id="emailTick"></div>
How can i do this ?
You need to Hide the Tick if the email validation fails :
function validateEmail(emailField){
var reg = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
if (reg.test(emailField.value) == false)
{
document.getElementById("emailTick").style.display='none'; // Hide tick if validation Fails
document.getElementById("emailCross").style.display='block';
return false;
}
document.getElementById("emailCross").style.display='none';
document.getElementById("emailTick").style.display='block';
return true;
}
This should to:
if (reg.test(emailField.value) == false) {
document.getElementById("emailTick").style.display='none';
document.getElementById("emailCross").style.display='block';
return false;
} else {
document.getElementById("emailCross").style.display='none';
document.getElementById("emailTick").style.display='block';
}

how to validate email [duplicate]

This question already has answers here:
How can I validate an email address in JavaScript?
(79 answers)
Closed 8 years ago.
I need to add to add the following characteristics to this form but I'm stuck. any help would b greatly appreciated. Thanks
One or more word characters
Exactly one at-sign
One or more word characters
Exactly one period Two or more characters that are a-z,
A-Z, 0-9, period, or hyphen
<!DOCTYPE html>
<html>
<head>
<script>
function validateForm()
{
var x=document.forms["myForm"]["email"].value;
var atpos=x.indexOf("#");
var dotpos=x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
{
alert("Not a valid e-mail address");
return false;
}
}
</script>
</head>
<body>
<form name="myForm" action="demo_form.asp" onsubmit="return validateForm();" method="post">
Email: <input type="text" name="email">
<input type="submit" value="Submit">
</form>
</body>
function isValidEmailAddress(emailAddress) {
var pattern = new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))#((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i);
return pattern.test(emailAddress);
};
This function will work in your case
To call it like this
if( !isValidEmailAddress( emailaddress ) ) { /* do stuff here */ }
keep in mind that no 100% regex email check exists!
Checkout this link
https://stackoverflow.com/a/2855946/2630817
Try this:
<script>
function validateForm(){
var email=document.forms["myForm"]["email"].value;
var filter = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if (!filter.test(email)) {
alert("Not a valid e-mail address");
return false;
}
return true;
}
</script>
Try this pure javascript:
function checkEmail() {
var email = document.getElementById('txtEmail');
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;
}

Javascript validate two textbox

The code below validate two nameserver textbox. As you can see there is redundancy in the javascript code. // validate textbox 1 and // validate textbox 2. Is there anyway I could just use one script.. you know I just want to use 1 validation function to validate two textbox. I'm sorry for my English I hope you all can understand me. Thank you.
<script type="text/javascript">
// validate textbox 1
function validate_domain(){
var nameserver1 = document.getElementById('nameserver1').value;
var domain_array = nameserver1.split('.');
var domain = domain_array[0];
//This is reguler expresion for domain validation
var reg = /^([A-Za-z0-9])+[A-Za-z0-9-]+([A-Za-z0-9])$/;
if(domain == ''){
alert("Please enter the domain name");
document.getElementsById('nameserver1').focus();
return false;
}
if(reg.test(domain) == false){
alert("Invalid character in domain. Only letters, numbers or hyphens are allowed.");
document.getElementsById('nameserver1').focus();
return false;
}
}
// validate textbox 2
function validate_domain(){
var nameserver1 = document.getElementById('nameserver1').value;
var domain_array = nameserver2.split('.');
var domain = domain_array[0];
//This is reguler expresion for domain validation
var reg = /^([A-Za-z0-9])+[A-Za-z0-9-]+([A-Za-z0-9])$/;
if(domain == ''){
alert("Please enter the domain name");
document.getElementsById('nameserver2').focus();
return false;
}
if(reg.test(domain) == false){
alert("Invalid character in domain. Only letters, numbers or hyphens are allowed.");
document.getElementsById('nameserver2').focus();
return false;
}
}
</script>
<fieldset class="inlineLabels">
<label for="name">Nameserver 1</label>
<input type="text" class="textInput" maxlength="255" size="30" value="" id="nameserver1" name="nameserver1">
<label for="data">Nameserver 2</label>
<input type="text" class="textInput" maxlength="255" size="30" value="" id="data" name="nameserver2">
</fieldset>
<button onclick="validate_domain(); submitForm('page1','directpage.php');" value="Validate" name="btn_validate" type="button" class="positive iconstxt icoPositive"><span>Save</span></button>
Well here is another approach:
function ValidateDomain(){
function CheckForBlank(domain, textBox){
if(domain == ''){
alert("Please enter the domain name");
document.getElementsById('nameserver1').focus();
return false;
}
}
function CheckForFormat(domain, textBox){
if(reg.test(domain) == false){
alert("Invalid character in domain. Only letters, numbers or hyphens are allowed.");
document.getElementsById('nameserver1').focus();
return false;
}
}
function GetDomainName(inputId){
var serverName = document.getElementById(inputId).value,
domain_array = serverName.split('.');
return domain_array[0];
}
var nameserver1 = GetDomainName('nameserver1'),
nameserver2 = GetDomainName('nameserver2'),
nameServerInput1 = document.getElementsById('nameserver1');
nameServerInput2 = document.getElementsById('nameserver2');
if (CheckForFormat(nameserver1,nameServerInput1) && CheckForBlank(nameserver1,nameServerInput1)
&& CheckForFormat(nameserver2,nameServerInput2) && CheckForBlank(nameserver2,nameServerInput2)){
//This means you are valid
return {
name1:nameserver1,
name2:nameserver2
}
}
return false;
}
Maybe like this:
<script type="text/javascript">
function validate_domain(){
validateTextBox('nameserver1');
validateTextBox('nameserver2');
}
function validateTextBox(tbName){
var nameserver1 = document.getElementById(tbName).value;
var domain_array = nameserver1.split('.');
var domain = domain_array[0];
//This is reguler expresion for domain validation
var reg = /^([A-Za-z0-9])+[A-Za-z0-9-]+([A-Za-z0-9])$/;
if(domain == ''){
alert("Please enter the domain name");
document.getElementsById(tbName).focus();
return false;
}
if(reg.test(domain) == false){
alert("Invalid character in domain. Only letters, numbers or hyphens are allowed.");
document.getElementsById(tbName).focus();
return false;
}
}
}
</script>
Saw this one at work. Played with it at home. Here's a working jsFiddle. Yes, it's overly complex, but I detest alert('annoying pop-up');.
I commented the source, so you would better understand why I wrote it like that.
sg522: It may not copy/paste into your code and work, but I don't know what the rest of your code is. Neither are we here to write your code for you. We are here to help you learn and become a more experienced programmer.
Please let us know if you have questions.
Happy coding!
UPDATE: Modified jsFiddle to work with Opera and Firefox 10.
Neither Opera or Firefox apparently allow cloneNode to be called without parameters now.
Opera also apparently does not allow chained variable declarations.
Take the id of the element you want to validate as a parameter of your function.
// validate textbox
function validate_domain(serverName){
var server = document.getElementById(serverName).value;
var domain_array = server.split('.');
var domain = domain_array[0];
//This is reguler expresion for domain validation
var reg = /^([A-Za-z0-9])+[A-Za-z0-9-]+([A-Za-z0-9])$/;
if(domain == ''){
alert("Please enter the domain name");
document.getElementsById(serverName).focus();
return false;
}
if(reg.test(domain) == false){
alert("Invalid character in domain. Only letters, numbers or hyphens are allowed.");
document.getElementsById(serverName).focus();
return false;
}
}
<script type="text/javascript">
// validate textbox
function validate_domain(ele){
var nameserver = ele.value;
var domain_array = nameserver.split('.');
var domain = domain_array[0];
//This is reguler expresion for domain validation
var reg = /^([A-Za-z0-9])+[A-Za-z0-9-]+([A-Za-z0-9])$/;
if(domain == ''){
alert("Please enter the domain name");
ele.focus();
return false;
}
if(reg.test(domain) == false){
alert("Invalid character in domain. Only letters, numbers or hyphens are allowed.");
ele.focus();
return false;
}
}
</script>
<fieldset class="inlineLabels">
<label for="name">Nameserver 1</label>
<input type="text" class="textInput" maxlength="255" size="30" value="" id="nameserver1" name="nameserver1">
<label for="data">Nameserver 2</label>
<input type="text" class="textInput" maxlength="255" size="30" value="" id="data" name="nameserver2">
</fieldset>
<button onclick="validate_domain(document.getElementById('nameserver1')); validate_domain(document.getElementById('nameserver2')); submitForm('page1','directpage.php');" value="Validate" name="btn_validate" type="button" class="positive iconstxt icoPositive"><span>Save</span></button>

Email validator

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 onchange in my html to trigger the function.
<input type="text" id="email" name="email" onchange="check();" />
function check() {
email = 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;
}
}
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>
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!
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.

Categories