I’m building a small “Validate” object which basically exposes a validate method and takes the id of one element and an array of validators and then returns true or false.
basically this is what i’d like to achieve
var Validator = function() {
var no_digits = function( el ) {
return true;
}
var no_uppercase_letters = function( el ) {
return true;
}
return {
validate: function( element_id, validators ) {
//here i would like to iterate on the validators array and for each
//element of the array i would like to check if a function of the same name
// exist and call that function passing the element
}
}
}();
and then call it like this
var element_valid = Validator.validate( 'myid', [ "no_digits", "no_uppercase_letters"] );
where the second parameter is an array of validators i’d like to call.
Any suggestion on a good object oriented approach?I would like to keep the validating functions private otherwise i could do
var Validator = function() {
return {
validate: function(element_id, validators) {
console.log(this);
this[validators]();
// Validator[validators](element_id);
},
no_digits: function(el) {
alert('hi');
return true;
},
no_uppercase_letters: function(el) {
return true;
}
}
}();
but i’d rather keep the no_gits an no_uppercase_letters function private
var element_valid = Validator.validate(‘myid’, “no_digits”);
It’s called the “Module pattern”. This pattern is more commonly known as simply “encapsulation” in JavaScript. Closures is another possibly but more specifically it is purely encapsulation in this case.
Encapsulation simply means you are making some members private. What is private in this case? Well the
noDigitsvariable is private in this case.