It consists of 2 functions one of which contains boolean variable set to true or false and the other expands it a bit.
It uses the event handler onSubmit in the form where the email field is placed.
I'll give some later commments in red as we go along.
|
<script Language="JavaScript"> function isEmailAddr(email) { var result = false /* This is a boolean variable that will be set to true or false later in the function */
var theStr = new String(email) var index = theStr.indexOf("@"); /* It gives the name for the entire email string and the substring of the email string starting from symbol "@" */
if (index > 0) { var dot = theStr.indexOf(".",index); if ((dot > index+2) && (theStr.length > dot+2)) result = true; } return result; } /* If "@" symbol exists in the main string it then identifies that part of the "@" substring that starts from "." symbol. If there's at least 2 symbols after "@" and at least 2 after "." it sets the boolean variable to true. If anything is not as specified above - then the function is boolean false */
function FormValidator(theForm) {
if (theForm.email.value == "") { alert("Please enter a value for the \"email\" field."); theForm.email.focus(); return (false); } /* This part checks if the email field is blank. If it is it gives an alert message */
if (!isEmailAddr(theForm.email.value)) { alert("Please enter a complete email address in the form: yourname@yourdomain.com"); theForm.email.focus(); return (false); } /* This part checks if the first function is false. if it is it then gives an alert message and points the cursor back to the field. */ return (true); } </script> |
This is the code you'll need to insert in the body of your html page:
<form method="POST" action="some server side script to go with JS" onsubmit="return FormValidator(this)"> <p>Email Address:</p> <input type="text" style="background-color:'#fff00f'" name="email" size="32"><input type="submit" value="Submit" name="submit"> </form> |
Please note that this script should work with a respective server-side script indicated in "action" to store email addresses in the database for instance. Happy coding!