Outline
I have a form that needs validation. The problem is that the software requires custom validation that depends on multiple parameters.
I decided to pass the object into a function which will dynamically give the object the functions it needs to be validated. Then once the validation is completed, I remove those functions from the object.
I'm adding the functions so I can chain them together, which I believe will provide me with great composition.
Usage
This is how I add the functions to the object:
let q = this.validator.validate(this.question)
I can then chain the added functions like this:
q.validateString().cleanUp();
That way my functions are composable and reusable.
Implementation
Now for the actual code to be reviewed:
export class Validator {
validate(question) {
let q = Object.assign(
{},
question,
validationOptions
);
return q;
}
}
let validationOptions = {
validateString,
cleanUp
};
function validateString() {
return this;
}
function cleanUp() {
Object.keys(validationOptions).map((i) => delete this[i]);
return this;
}
I'm forced to use the class because I need Aurelia Dependency Injection. I compose my functions outside of that class Validator
because they only need to work with the this
binding.
This code works perfectly, and it executes as expected; however, I do have a few concerns:
- Is there a downside to the way I add these functions?
- The way I remove these functions works well, but are there better options? I can't use
Symbol
because I return theq object
to another class.