I am trying to create a custom javascript form validator. I am starting by creating an input validator base class, and I am extending this base class to handle more specific input types. For example, income and zipcode.
Current structure is as follows: Base Class = InputValidator, Sub Classes: Income, ZipCode
Things are working as expected when I create only one instance of Income. However, if I also create an instance of ZipCode, it appears to overwrite the base class of Income. To see this in action, I have created a JSFiddle. http://jsfiddle.net/tpdietz/wy274ymb/3/
If you type in anything other than a digit for the annual income input, you should see a warning drop down above the income input. This is what I want. However, if you uncomment line 48 in the jsfiddle, re run it, and try the same thing. You will see that typing in something incorrect for the annual income, invokes the zip code warning. As expected, typing in something other than a digit for the zip code does the same thing.
Here is how I am declaring the sub classes:
var Income = function (incomeElement, warningElement) {
InputValidator.call(this, incomeElement, warningElement, isInteger);
this.isValid = function() {
return valid;
}
}
var ZipCode = function (zipCodeElement, warningElement) {
InputValidator.call(this, zipCodeElement, warningElement, isInteger);
this.isValid = function() {
return valid && ele.val().length < 6 && ele.val().length > 2;
}
}
and here is how I declare the base class:
var InputValidator = function (element, warningElement, validatorIn) {
this.name = name;
ele = element;
warning = warningElement;
validator = validatorIn;
valid = false;
ele.keyup(function() {
if(!validator($(this).val())) {
showWarning();
valid = false;
} else {
hideWarning();
valid = true;
}
});
function showWarning() {
warning.slideDown();
}
function hideWarning() {
warning.slideUp();
}
}
Does anybody have any idea why this is happening? I thought I had a grasp on how this should work.
Thank you.