Q. What if we want to test for a string pattern other than "null" or "empty"?...
A. Regular Expressions!
Simplified Regular Expression for an email address:
/^[\w\._-]+@[\w\._-]+\.[a-zA-Z]{2,7}$/
^
[\w\._-]+
@
\.[a-zA-Z]{2,7}
$
<form onsubmit="return Validate(this)" method="get" action="http://cscie12.dce.harvard.edu/echo">
<div><label for="email1">Email Address</label>:
<input type="text" size="32" name="email" id="email1"/><br/>
<input type="submit"/></div>
</form>
In head
element:
<script type="text/javascript" src="example9.js"> </script>
Contents of example9.js
/* validates that the entry is formatted as an email address */
function Validate(thisForm) {
var tocheck = thisForm.email.value;
var re = /^[\w\._-]+@[\w\._-]+\.[a-zA-Z]{2,7}$/;
if (!tocheck.match(re)) {
alert("Please verify the email address format.");
thisForm.email.focus();
thisForm.email.style.backgroundColor = '#ff9';
return false;
} else {
return true;
}
}
Copyright © David Heitmeyer