I am working on a validator library, coming from PHP I would like to give the validation a similar set up with Validators and Constraints (The value, object gets validated by the validators against the selected constraints).
So working on the Constraints I have following issue:
The constraints all share the same properties just the implementation is slightly different.
Example:
Constraint = Validator.Constraint = {
name: null, // contains the name of the constraint
value: null, // contains the value which we want to validate
options: {}, // contains options for some Constraints (e.g. range)
message: null, // contains the error message which is getting returned
validate: function(){}, // the validation logic
constructor: function(value, options){
this.value = value;
this.options = options;
this.validate();
} // the constructor which can be called for stand-alone validation
};
Now I would like to somehow extend the Constraint and customize it:
RequiredConstraint = Validator.RequiredConstraint = {
name: "required",
message: "this property is required",
validate: function(){
if (this.value != "" || this.value != undefined || this.value != null) {
return;
}
return this.message;
}
// other properties get inherited
};
The constrain then should be usable with:
RequiredConstraint("");
// returns false
I know would like to know two things:
- At first if it is at all recommand to use this programming style even JavaScript is another language and too dynamic for this?
- If it is still good practis how could I implement such behaviour as descriped above?
What keywords do I have to look for?
Regards
You need to put your functions in the prototype if you want them to be inherited.
Also, in ES3, the cleanest objects to inherit from are Functions.
Example: