var $ = function (id) { return document.getElementById(id);} var fields = []; // Define field objects fields["email"] = {}; fields["firstname"] = {}; fields["lastname"] = {}; fields["zip"] = {}; // Default field messages fields["email"].message = "Must be a valid email address."; fields["zip"].message = "Use 5 digit ZIP code."; // Field errors fields["email"].required = new Error("Email is required."); fields["email"].invalid = new Error("Email is not valid."); fields["first_name"].required = new Error("First name is required."); fields["last_name"].required = new Error("Last name is required."); fields["zip"].required = new Error("ZIP Code is required."); fields["zip"].invalid = new Error("ZIP Code is not valid."); // Field validation functions fields["email"].validate = function () { var email = $("email").value; if (email.length == 0) throw this.required; var parts = email.split("@"); if (parts.length != 2 ) throw this.invalid; if (parts[0].length > 64) throw this.invalid; if (parts[1].length > 255) throw this.invalid; var local_part = /^([-\w!#$%&'*+-/=?^`{ | }~]+)|("[^"]*")$/; var local_dots = /(^\.)|(^[^"].*\.\..*[^"]$)|(\.$)/; if ( !parts[0].match(local_part) ) throw this.invalid; if ( parts[0].match(local_dots) ) throw this.invalid; var host_pattern = "(([a-zA-Z0-9])\\.|([a-zA-Z0-9][-a-zA-Z0-9]{ 0,62 }[a-zA-Z0-9])\\.)+"; var tld_pattern = "[a-zA-Z0-9]{ 2,6 }"; var domain = new RegExp("^" + host_pattern + tld_pattern + "$"); if ( !parts[1].match(domain) ) throw this.invalid; } fields["firstname"].validate = function () { var first_name = $("first_name").value; if ( first_name.length == 0 ) throw this.required; } fields["lastname"].validate = function () { var last_name = $("last_name").value; if ( last_name.length == 0 ) throw this.required; } fields["zip"].validate = function () { var zip = $("zip").value; if ( zip.length == 0 ) throw this.required; var zip_pattern = /^[\d]{ 5 }(-[\d]{ 4 })?$/; if ( !zip.match(zip_pattern) ) throw this.invalid; } window.onload = function(){ $("button").onclick = fields["zip"].validate; }