Email Address Validation Script
Using the string methods covered in the previous tutorial group, we can check to see if a form field contains a valid email address.
This sample email address validation script checks the email address for the format, "
[email protected]", where x represents at least one character in that position, and the character(s) can be anything except "@" and adjacent "."'s. So the addresses, "
[email protected]" and "
[email protected]" are valid but "@jj.com", "j@@j.com", "j@jcom", "
[email protected]", ".j@jcom" and "j@jcom." are not valid.
To execute validation when form is submitted, then either cancel or continue submit:
<form onsubmit="return checkEmail(this.email)">
<input type="text" name="email">
<input type="submit">
</form>
To execute validation when mouse moves out of text field (does not intervene with submittal process):
<form>
<input type="text" name="email" onblur="checkEmail(this)">
</form>
To execute validation when an image is used to submit the form::
<form name="imageForm">
<input type="text" name="email">
<a href="javascript:submitForm()"><img src="../images/submitImg.gif" border="0"></a>
</form>
Notice I did not use a form input type of image. Instead, I wrapped an image in <a> tags containing a call to a separate function, ensuring that older browsers submit the form properly. The function, "submitForm()", that is invoked when the image is clicked on, contains the built-in form method, "submit()".
function submitForm(){
var myForm = document.imageForm
var eField = myForm.email
if(checkEmail(eField) != false){
myForm.submit()
}
}
Here is the Email Validation Script in its entirety:
function checkEmail(emField){
var fieldValue = emField.value
if(fieldValue != ""){
var atSymbol = 0
for(var a = 0; a < fieldValue.length; a++){
if(fieldValue.charAt(a) == "@"){
atSymbol++
}
}
if(atSymbol > 1){
alert("Please Enter A Valid Email Address")
return false
}
if(atSymbol == 1 && fieldValue.charAt(0) != "@"){
var period = fieldValue.indexOf(".",fieldValue.indexOf("@")+2)
var twoPeriods = (fieldValue.charAt((period+1)) == ".") ? true : false
if(period == -1 || twoPeriods || fieldValue.length < period + 2 || fieldValue.charAt(fieldValue.length-1)=="."){
alert("Please Enter A Valid Email Address")
return false
}
}
else{
alert("Please Enter A Valid Email Address")
return false
}
}
else{
alert("Please Enter A Valid Email Address")
return false
}
alert("VALID EMAIL ADDRESS!")
return true
}
function submitForm(){
var myForm = document.imageForm
var eField = myForm.email
if(checkEmail(eField) != false){
myForm.submit()
}
}