I'm creating an html5 JS form library. The idea is to turn elements with a class of .form-item into content editable divs, using the elements' data-attributes as instructions for the type of form item, validation, etc that should be created.
The code below creates a validation object for a single form item that checks to see if the minimum length of the field value is met. The object's properties include the DOM element it applies to (el), the minimum length for the field (minLen), the error message (msgError) that should be displayed if that minimum length is not met, and a function (submit) that returns whether the object validates, displaying the error message if it does not.
However, the submit property function always returns false. I'm pretty sure I know why, but I'm not sure of the best way to correct it. I believe the problem I'm running into has to do with the notion of a closure. The submit property checks the length of the innerHTML of the form item element and compares it to the minLen property. But I think this only happens at the moment of instantiation of the validation object, when the innerHTML.length is always 0 (because the form item, and the validation object, must be created prior to the user being able to enter anything into the field). How should I modify the below code so that the submit property function runs anew any time it is called (thereby checking the current length of the innerHTML of the field, rather than the length at the moment of instantiation)?
function formValidateMinLen(item){
var minLen = item.attr('data-minLen');
this.el = item;
this.minLen = minLen;
this.msgError = item.attr('data-error_minLen');
this.submit = function(){
if(this.el.html() >= this.minLen){
return true;
}else{
this.el.after('<div class="msgError">' + this.msgError + '</div>');
return false;
}
}
}
item = new formValidateMinLen($('#registration-form .form-item:first'));
I did come up with one solution, which is to pass the innerHTML of the form item element as an argument to the submit property function, like this:
this.submit = function(html){
if(html >= this.minLen){
...
}
item = new formValidateMinLen($('#registration-form .form-item:first'));
item.submit($('#registration-form .form-item:first').html());
However, I don't like that solution because it seems redundant to have to re-specify the DOM element in the item.submit code (since the object already contains that DOM element in its el property).
So... what should I do?
I'm an idiot. I was comparing the innerHTML to the minimum length, rather than the LENGTH of the innerHTML to the minimum length. Now it works :)