Harvard Extension School
CSCI E-12 Fundamentals of Web Site Development | Spring 2019

## 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

Example 8.9 - Form Validation with Regular Expressions - Example 8.9 | JavaScript example9.js | <form onsubmit="return Validate(this)" method="get" action="http://cscie12.dce.harvard.edu/echo" enctype="application/x-www-form-urlencoded"><div><label for="email1">Email Address</label>: <input type="text" size="32" name="email" id="email1"/><br/><input type="submit"/></div></form>

- Markup
- Script
- Screenshot

    <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