JaZahns Week10 Form Validation
using a form object
by Lucille Kenney
HTML
<form id="myform">
<fieldset>
<legend>My Pretty Form</legend>
<div>
<label for="fname">First Name:</label> <input name="fname" type="text" />
</div>
<div>
<label for="lname">Last Name:</label> <input name="lname" type="text" />
</div>
<div>
<label for="phone">Phone:</label> <input name="phone" type="text" />
</div>
<div>
<label for="email">Email:</label> <input name="email" type="text" />
</div>
<div id="errors"></div>
<div>
<input type="submit" value="Submit" />
</div>
</fieldset>
</form>
CSS
label {
float: left;
width: 100px;
}
form div {
padding-bottom: 5px;
}
.error {
color: red;
}
JavaScript
/**
* Form Object
* @param {object} form - DOM element
* @param {object} obj.form - form DOM element
* @param {string} obj.fname - first name
* @param {string} obj.lname - last name
* @param {string} obj.phone - phone number
* @param {string} obj.email - email addr
*/
var Form = function(obj){
// if there is no form given, set it to the first form on the page
this.form = obj.form || document.getElementByTagName("form")[0];
// for initial values
this.fname = obj.fname || '';
this.lname = obj.lname || '';
this.phone = obj.phone || '';
this.email = obj.email || '';
// error messages
this.errors = [];
this.init();
};
/**
* @function init
* initializes the values sent to Form
*/
Form.prototype.init = function(){
var that = this;
// set the initial values
['fname', 'lname', 'phone', 'email'].forEach(function(propName){
that.form.elements[propName].value = this[propName];
}, this);
this.form.addEventListener("submit", function(event){
// collect values
that.fname = that.form.elements["fname"].value;
that.lname = that.form.elements["lname"].value;
that.phone = that.form.elements["phone"].value;
that.email = that.form.elements["email"].value;
that.validate();
if(that.errors.length > 0){
event.preventDefault();
} else {
// send to server
document.getElementById("errors").innerHTML = "Submitted!";
event.preventDefault();
}
that.errors = [];
});
};
/**
* @function validate
*/
Form.prototype.validate = function(){
this.validatePhone();
this.validateEmail();
if(this.errors.length > 0){
this.displayErrors();
}
};
/**
* @function validatePhone
*/
Form.prototype.validatePhone = function(){
var numbersonly = this.phone.length > 0 ? this.phone.match(/\d+/g).join("") : '';
// check...