Solved

Validating Emal and phone numbers in javascript

Posted on 2009-04-12
12
1,195 Views
Last Modified: 2012-05-06
I am creating an online application and would like to be able to validate the email address entered along with the required phone number entered. Below is the JS code I have so far, it currently only checks the input and select fields. I'v tried different routes but I keep hitting a dead wall. I would think it would be straight forward but my eyes are beginning to go cross eyed.

Also, though not a big deal, when a field is flagged "invalid" the JS is suppose to highlight the background of the input fields yellow and surrond them in a 2px red boarder but its not doing that. This is done through the CSS. Info regarding this issue would be a plus, but again it's no big deal for now.

Additionally, I don't have a firm grasp on JS so speak in "little words" :p
JS Code:
---------
function validate(theForm){
  var elems = theForm.elements;
  for (var i=0; i<elems.length; i++) {
    if (elems[i].nodeName == "INPUT" || elems[i].nodeName == "SELECT") {
      if (elems[i].className.indexOf("invalid") !=-1 || elems[i].className.indexOf("reqd")!=-1) {
		  if (elems[i].value=="" || elems[i].selectedIndex == 0) {
		  elems[i].className="invalid";
          elems[i].focus();
          return false
        }
        else elems[i].className = "reqd"; // reset
      }
    }
 }
 return true; // allow submit
}
 
function validateEmail(myemail) {
	alert("Validate Email function called.");
function validatePhone(myphone) {
alert("Validate Phone function called.");
 
HTML CODE:
----------
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" type="text/css" href="CSS/layout.css">
<link rel="stylesheet" type="text/css" href="CSS/application.css">
 
<script type="text/javascript" src="Scripts/validate.js"></script>
 
<title>RN Resources, LLC</title>
</head>
 
<body class="oneColFixCtrHdr">
 
<div id="container">
  <div id="header">
    <!--Header jpg will display here.-->
    <div id="navMenu">
    			<ul>
        			<li><a href="index.html" class="home"> </a></li>
                    <li><a href="faq.html" class="faq"> </a></li>
        			<li><a href="about.html" class="about"> </a></li>
    			</ul>
    <!-- end #navMenu --></div>
    <!-- end #header --></div>
  <div id="appContent">
        	<table width = "700" border="0" align="left" celpadding="" cellspacing="1">
            	<form name="applicationform" onsubmit="return validate(this)" action="#"> 
            	<table width="100%" border="0" cellspacing="5" cellpadding="3">
                <!--Personal Information -->
                <table><!--Table for Title Layout-->
                <tr>
                    <td><strong>Personal Information</strong></td>
                </tr>
                <tr>
                	<td>* donates required fields</td>
                </tr>
                </table>
                <table><!--Table for input layout-->
                <tr>
                	<td>&nbsp;</td>
                </tr>
                <tr>
                    <td width="42%">*Last Name</td>
                    <td width="42%">*First Name</td>
                    <td width="16%">*Middle Initial:</td>
              	</tr>
                <tr>
                    <td><input name="lastname" type="text" id="lastname" size="25" maxlength="25" class="reqd"/></td>
                    <td><input name="firstname" type="text" id="firstname" size="25" maxlength="25" class="reqd" /></td>
                    <td><input name="middlename" type="text" id="middlename" size="1" maxlength="1" class="reqd" /></td>
                </tr>
                <tr>
                    <td>Other names you are known under:</td>
                </tr>
                <tr>
                    <td><input name="oname" type"text" id="othername" size="38" /></td>
                </tr>
                <tr>
                    <td>*Home Phone:</td>
                    <td>Mobil Phone:</td>
                </tr>
                <tr>
                    <td><input name="hphone" type="text" id="homephone" size="15" maxlength="14" class="reqd" /></td>
                    <td><input name="mphone" type="text" id="mobilphone" size="15" maxlength="14" /></td>
                </tr>
                <tr>
                    <td>*Email Address:</td>
                </tr>
                <tr>
                    <td><input name="appmail" type="text" id="appemail" size="25" maxlength"25" class="reqd" /></td>
                </tr>
                <tr>
                    <td>Social Security Number: (OPITIONAL)</td>
                </tr>
                <tr>
                    <td><input name="socialnumber" type="text" id="socialnumber" size="10" maxlength="10"/>&nbsp; No dash's</td>
                </tr>
                <tr>
                    <td>*Discipline:</td>
                    <td>*Current Specialty:</td>
                    <td>*Years in Specialty:</td>
                </tr>
                <tr>
                    <td><select name="discipline" id="discipline" class="reqd">
                        <option value="selectdiscipline" >Please select a discipline...</option>
                        <option value="RN" class="disciplineRN">RN</option>
                        <option value="CNA" class="disciplineCNA">CNA</option>
                        </select></td>
                	<td><select name="specialty" id="specialty" class="reqd">
                        <option value="selectspeclty">Please select a specialty...</option>
                        <option value="MS">M/S</option>
                        <option value="ICU">ICU</option>
                        <option value="ER">ER</option>
                        <option value="Psych">Psych</option>
                        <option value="OB">OB</option>
                        <option value="Tele">Tele</option>
                        </select></td>
                    <td><select name="yearspecialty" id="yearsspecialty" class="reqd">
                        <option value="selectyears">Please select years...</option>
                        <option value="zerotwo">0 - 2</option>
                        <option value="twosix">2 - 6</option>
                        <option value="sixten">6 - 10</option>
                        <option value="plusten">10+</option>
                        </select></td>
                </tr>
                <tr>
                	<td>&nbsp;</td>
                </tr>
                <tr>
                    <td>*Have you ever worked as a traveler?:</td>
                </tr>
                <tr>
                    <td>Yes: <input type="radio" name="worked" value="yes" id="worked" > No: <input type="radio" name="worked" value="no" id="worked" checked="checked"></td>
                </tr>
                <tr>
                	<td>Date avaliable to work: (mm/dd/yyyy)</td>
                </tr>
                <tr>
                    <td><input name="avaliabledate" type="text" id="avaliabledate" size="15" /></td>
                </tr>
                <tr>
                	<td>&nbsp;</td>
                </tr>
                </table>
                <!--End Personal Information-->
                <!-- Start Address Information -->
                <table>
                 <tr>
                    <td><strong>Address Information</strong></td>
                </tr>
                <tr>
                	<td>&nbsp;</td>
                </tr>
                </table>
                <table width="70%" border="0" cellspacing="3" cellpadding="3">
                <tr>
                    <td width="25%">Current Address:</td>
                    <td width="25%"></td>
                    <td width="20%"></td>
                 </tr>
                 <tr>
                    <td>*Street Address:</td>
                    <td>*Country</td>
                 </tr>
                 <tr>
                    <td><input name="currentaddress" type="text" id="currentaddress" size="25" maxlength="25" class="reqd"/></td>
                    <td><input name="currentcountry" type="text" id="currentcountry" size="25" maxlength="25" class="reqd"/></td>
                 </tr>
                 <tr>
                    <td>*City</td>
                    <td>*State/Province:</td>
                    <td>*Zip/Postal code:</td>
                 </tr>
                 <tr>
                    <td><input name="currentcity" type="text" id="currentcity" size="25" maxlength="25" class="reqd" /></td>
                    <td><input name="currentstate" type="text" id="currentstate" size="25" maxlength="25" class="reqd" /></td>
                    <td><input name="currentzip" type="text" id="currentzip" size="10" maxlength="10" class="reqd" /></td>
                 </tr>
                 <tr>
                    <td>Permanent Address:</td>
                 </tr>
                 <tr>
                    <td>Street Address:</td>
                    <td>Country</td>
                 </tr>
                 <tr>
                    <td><input name="permanentaddress" type="text" id="permanentaddress" size="25" /></td>
                    <td><input name="permanentcountry" type="text" id="permanentcountry" size="25" /></td>
                 </tr>
                 <tr>
                    <td>City</td>
                    <td>State/Province:</td>
                    <td>Zip/Postal code:</td>
                 </tr>
                 <tr>
                    <td><input name="permanentcity" type="text" id="permanentcity" size="25"  /></td>
                    <td><input name="permanentstate" type="text" id="permanentstate" size="25"  /></td>
                    <td><input name="permanentzip" type="text" id="permanentzip" size="10"  /></td>
                 </tr>
                 <tr>
                 	<td>&nbsp;</td>
                 </tr>
                 </table>
                 <!-- End Address information -->
                 <!-- Start Emegency Contact -->
                 <table width="60%" border="0" cellspacing="3" cellpadding="3"> 	
                 <tr>
                    <td width="20%"><strong>Emergency Contact</stong></td>
                    <td width="20%">
                    <td width="20%">
                 </tr> 
                 <tr>
                 	<td>&nbsp;</td>
                 </tr>    
                 <tr>
                    <td>Name of contact:</td>
                    <td>Relationship:</td>
                    <td>Phone:</td>
                 </tr>
                 <tr>
                    <td><input name="emergencyname" type="text" id="emergencyname" size="25" /></td>
                    <td><input name="emergencyrelation" type="text" id="emergencyrelation" size="25" /></td>
                    <td><input name="emergencyphone" type="text" id="emergencyphone" size="12" /></td>
                 </tr>
                 <tr>
                    <td>Street Address:</td>
                    <td>Country</td>
                 </tr>
                 <tr>
                     <td><input name="emergencyaddress" type="text" id="emergencyaddress" size="25" /></td>
                     <td><input name="emergencycountry" type="text" id="emergencycountry" size="25" /></td>
                 </tr>
                 <tr>
                     <td>City</td>
                     <td>State/Province:</td>
                     <td>Zip/Postal code:</td>
                 </tr>
                 <tr>
                     <td><input name="emergencycity" type="text" id="emergencycity" size="25"  /></td>
                     <td><input name="emergencystate" type="text" id="emergencystate" size="25"  /></td>
                     <td><input name="emergencyzip" type="text" id="emergencyzip" size="10"  /></td>
                 </tr>
                 <tr>
                 	<td>&nbsp;</td>
                 </tr> 
           		 </table>
                 <!-- End Emergency Contact Information -->
                 <!-- Start License/Registaration/Certification --->
                 <table width="60%" border="0" cellspacing="3" cellpadding="3">
                 <tr>
                 	<td><strong>License:</strong></td>
                 </tr>
                 <tr>
                	<td>&nbsp;</td>
                </tr> 
                <tr>
                    <td>*License type:</td>
                    <td>*License number:</td>
                </tr>
                <tr>
                    <td><select name="firstlicense" id="firstlicense" class="reqd">
                        <option value="firstselectlicense">Please select a license type</option>
                        <option value="RN">RN</option>
                        <option value="CNA">CNA</option>
                        </select></td>
                    <td><input name="firstlicensenumber" type="text" id"firstlicensenumber" size="30" maxlength="30" class="reqd" /></td>
                </tr>
                <tr>
                    <td>*State/Province:</td>
                    <td>*Expiration date:</td>
                </tr>
                <tr>
                    <td><input type="text" name="firststatelicense" id="firststatelicense" size="25" maxlength="25" class="reqd" /></td>
                    <td><input type="text" name="firstexpirationlicense" id="firstexpiration" size="10"  maxlength="10" class="reqd"/></td>
                </tr>
                <tr>
                	<td>License type:</td>
                	<td>License number:</td>
                </tr>
                <tr>
                    <td><select name="secondlicense" id="secondlicense">
                        <option value="secondselectlicense">Please select a license type</option>
                        <option value="RN">RN</option>
                        <option value="CNA">CNA</option>
                        </select></td>
                    <td><input name="secondlicensenumber" type="text" id"secondlicensenumber" size="30" /></td>
                </tr>
                <tr>
                    <td>State/Province:</td>
                    <td>Expiration date:</td>
                </tr>
                <tr>
                    <td><input type="text" name="secondstatelicense" id="secondstatelicense" size="30" /></td>
                    <td><input type="text" name="secondexpirationlicense" id="secondexpiration" size="10"  /></td>
                </tr>
                </table>
                   <!-- End License Information -->
                <!-- Start of submit button -->
                <table>
                <tr>
                	<td><input type="submit" value="Submit"  /> </td>
                </tr>
                </table>
                <!-- End submti button -->
            </table>
            
        </form>
  <!-- end #mainContent --></div>
  <div id="footer">
    <!--Footer jpg will display here.-->
    <p>Copyright © 2009-2010. RN Resources, LLC all rights reserved.</p>
  <!-- end #footer --></div>
<!-- end #container --></div>
</body>
</html>

Open in new window

0
Comment
Question by:neonate928
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 6
  • 6
12 Comments
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 24130409
Can you post the other files?
0
 

Author Comment

by:neonate928
ID: 24130626
I hope you mean the CSS file.
CSS CODE:
-------------
@charset "utf-8";
/* CSS Document */
 
.invalid {
	background-color: #FF9;
	boarder: 2px red inset;
}
 
.oneColFixCtrHdr #appContent td strong {
	font-family:Arial, Helvetica, sans-serif;
	font-size:16px;
}

Open in new window

0
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 24130715
Actually I did not see the JS was in the top of the post

I thought we already FIXED this???
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Author Comment

by:neonate928
ID: 24131213
Yes, but as I said in the previous question, my online application is going to grow. Seeing how I am trying to learn JS I am moving in small junks. The code does work and you don't know how thankful I am that you made this alot more simple than what the book does that I am using. As you may already see I made some changes to you code in order to accomidate for other fields beside the original text field type you provided. Right now I cannot figure out how to add further capability to validate the email and phone number fields.  In other words when the elems[i] appraoches the email and phone text fields I want to have them validated by calling the functions I have for each, that for right no do nothing but alert the user the function has been called. After I ensure the email and phone fields are correct my next junk of the application is to see to have the JS check to see if a check box is checked "Yes" and if so then the user will need to write the reason in the accompined text field to the check box. Than I should be done with the JS validation.

Once I have this completed I wil have the application submit the applicatoin to my email using PHP.

Thats my full plan as it stands right now for my online application.
0
 

Author Comment

by:neonate928
ID: 24133415
Anyone have some idea's on how I can check to see if elems[i] is the input field for email, in which than it calls my validateEmail function. I have tried different methods such as getElementById and comparing it to "appemail" I have also tried getElementByName but neither one of these methods seems to work. Any suggestions would be great.
0
 

Author Comment

by:neonate928
ID: 24133744
Ok I changed the class name in my input email field to reqd email. And have thus changed the JS code to validate the email. However, my validEmail function is not running right. If someone could blease take a look that would be great. Thanks!
function validate(theForm){
  var elems = theForm.elements;
  for (var i=0; i<elems.length; i++) {
		if (elems[i].nodeName == "INPUT" || elems[i].nodeName == "SELECT") {
			//validate email input
			if(elems[i].className.indexOf("reqd email") !=-1) {
				if(!validEmail(elems[i].value)) {
					elems[i].className="invalid";
					elems[i].focus();
					return false
				}
			}
		  if (elems[i].className.indexOf("invalid") !=-1 || elems[i].className.indexOf("reqd")!=-1) {
			  if (elems[i].value=="" || elems[i].selectedIndex == 0) {
			  elems[i].className="invalid";
			  elems[i].focus();
			  return false
			}
			else elems[i].className = "reqd"; // reset
      }
    }
 }
 return true; // allow submit
}
 
function validEmail(myemail) {
	var invalidChars = " /:,;!#$%^&*()[]{}~`";
	
	if(myemail == "") {
		return false;
	}
	
	for(var i=0; i < invalidChars.length; i++) {
		var badChar = invalidChars.charAt(i);
		if(myemail.indexOf(badChar) > -1) {
			return false;
		}
	}
	
	var atPos = myemail.indexOf("@",1);
	if(atPos == -1) {
		return false;
	}
	if(myemail.indexOf("@",atPos+1) != -1) {
		return false;
	}
	
	var periodPos = myemail.indexOf(".",atPos);
	if(periodPos == -1) {
		return false;
	}
	if(perodPos+3 > myemail.length) {
		return false;
	}
	return true;
}

Open in new window

0
 

Author Comment

by:neonate928
ID: 24133823
I got the validEmail function to work. I also made some changes to the valid email function too.
function validEmail(myemail) {
	var emailstring = myemail;
	var ampIndex = emailstring.indexOf("@");
	var afterAmp = emailstring.substring((ampIndex + 1), emailstring.length);
		// find a dot in the portion of the string after the ampersand only
	var dotIndex = afterAmp.indexOf(".");
		// determine dot position in entire string (not just after amp portion)
	dotIndex = dotIndex + ampIndex + 1;
		// afterAmp will be portion of string from ampersand to dot
	afterAmp = emailstring.substring((ampIndex + 1), dotIndex);
		// afterDot will be portion of string from dot to end of string
	var afterDot = emailstring.substring((dotIndex + 1), emailstring.length);
	var beforeAmp = emailstring.substring(0,(ampIndex));
	var email_regex = /^\w(?:\w|-|\.(?!\.|@))*@\w(?:\w|-|\.(?!\.))*\.\w{2,3}/ 
		// index of -1 means "not found"
	if ((emailstring.indexOf("@") != "-1") &&
		(emailstring.length > 5) &&
		(afterAmp.length > 0) &&
		(beforeAmp.length > 1) &&
		(afterDot.length > 1) &&
		(email_regex.test(emailstring)) ) {
		  return true;
	} else {
			return false;
	}
}

Open in new window

0
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 24135089
So me being in CET and not awake until now made you fix your own code. Well done. So I will take a look later. Anything left you are not happy with?
0
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 24135101
Ok. Had a quick look at the email validation. I see you like to wear belt and suspenders.
I'll post a simpler one in a few hours
0
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 24135482
As promised - but I believe your test for the email needs to look differently (at least the one you posted) since it does not reset the classname when it is valid - so perhaps test the name instead?



// http://regexlib.com/DisplayPatterns.aspx - narendiran dorairaj 
var emailReg = /^(([a-zA-Z0-9_\-\.]+)@([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5}){1,25})+([;.](([a-zA-Z0-9_\-\.]+)@([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5}){1,25})+)*$/
function validEmail(str) {
  return emailReg.test(str);
}

Open in new window

0
 

Author Comment

by:neonate928
ID: 24138700
I still got go figure out how to check the phone number entered, I also will need to be able to check if a check box is marked yes and if so then to see if the input text field next to it is filled out. Than I will be done.

As for wearing suspenders, I am learning so I know I am not going the cleanest and easiest way possible as I don't know or fully understand the code quite yet. It was the same way when I was learning C++. Any help is greatly appreciated.
0
 
LVL 75

Accepted Solution

by:
Michel Plungjan earned 500 total points
ID: 24138776
http://regexlib.com/DisplayPatterns.aspx?cattabindex=6&categoryId=7

and

if (elems[i].nodeName == "INPUT" && elems[i].type == "checkbox"  && elems[i].checked) {
  if (elems[i].nextSibling.nodeName=='INPUT' && elems[i].nextSibling.type=='text' && elems[i].nextSibling.value=="") {
    alert('Please enter a value');
    elems[i].nextSibling.focus();
    return false
  }
}
.
.
return true
0

Featured Post

Revamp Your Training Process

Drastically shorten your training time with WalkMe's advanced online training solution that Guides your trainees to action.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article discusses four methods for overlaying images in a container on a web page
Boost your ability to deliver ambitious and competitive web apps by choosing the right JavaScript framework to best suit your project’s needs.
In this tutorial viewers will learn how to embed videos in a webpage using HTML5. Ensure your DOCTYPE declaration is set to HTML5: "<!DOCTYPE html>": Use the <video> tag to insert a video. Define the src as the URL of your video; this is similar to …
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…
Suggested Courses

630 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question