Form Validation and Regular Expressions
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}$/
^
- beginning of the string
[\w\._-]+
- [square brackets] indicate a character class
- "\w" is a word character
- "+" means 1 or more times
@
- the "@" part of the email address
\.[a-zA-Z]{2,7}
- matches the TLD (dot something, where something is 2 to 7 letters
$
- end of string
<form onsubmit="return Validate(this)" method="get" action="https://cscis12.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 src="example9.js"> </script>
Contents of example9.js
/* validates that the entry is formatted as an email address */
function Validate(thisForm) {
let tocheck = thisForm.email.value;
let 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;
}
}