Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: Web
Expertise: Intermediate
May 21, 1999

Validate E-Mail Addresses Using JavaScript

Using a text box and submit button, you can validate an e-mail address to make sure there is only one @ sign and that it is not at the beginning or end of the address. Also, you can check to ensure there is at least one period in the address and any periods are not at the beginning or end of the address. To do the validation, all you'll need is the JavaScript String.indexOf() function. This searches a string and returns the first instance of a substring. Using indexOf() you can search either from the beginning or a specific starting point. This code also makes sure that the required period is after the required @ sign. Finally, you can give appropriate alert responses to whether the requirements have been met.
 

<HTML>
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
<!--
function checkEMail(inEmail) {
	var locAt;
	var locPeriod;
	var okEmail;

	locAt = inEmail.indexOf("@");
	okEmail = ((locAt != -1) && 
			   (locAt != 0) &&
			   (locAt != (inEmail.length - 1)) &&
			   (inEmail.indexOf("@", locAt + 1) == -1)
			  );
	if (okEmail) {
		// so far, so good
		locPeriod = inEmail.indexOf(".");
		okEmail = ((locPeriod != -1) && (locPeriod != (inEmail.length - 1)) && (locPeriod > locAt));
	}
	
	return okEmail;
}

function alertUser(inEmail) {
	if (checkEMail(inEmail)) {
		alert("Your e-mail address is ok.");
	} else {
		alert("Your e-mail address is invalid.");
	}
}
// -->
</SCRIPT>
</HEAD>
<BODY>

<FORM>
Your e-mail address: <INPUT TYPE="TEXT" NAME="email" VALUE="javapro@feldmangroup.com" SIZE="30">
<INPUT TYPE="BUTTON" VALUE="Check Address" onClick="alertUser(this.form.email.value)">
</FORM>

</BODY>
</HTML>
Boris Feldman
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date