I am performing basic form validation using the code below and am wanting to achieve the same result using an object initializer. I am looking at other ways of coding the validation of the form. I am unsure whether there is an added advantage in using an object as opposed to an array. This lack of knowledge is because I am new to the world of javascript.
Code
var formID = document.forms["webform"];
function validateForm() {
var formFields = ["salutations", "fname", "lname"];
var formLabel = ["Salutations", "First Name", "Last Name"];
for(var i = 0; i < formFields.length; i = i + 1) {
if (formID[formFields[i]].value.length == 0) {
window.alert("The field " + formLabel[i] + " is empty");
return false;
}
}
}
OO is probably overkill for this. Reuse can be accomplished by passing the
formFieldsandformLabelsintovalidateForm:You could also pass all the variables you need in as an object:
However, if you want / need an OO pattern then simply create a constructor function:
This could then be used in this manner: