From e78c535659225fe7bc8b6488fa670f36deb4ef78 Mon Sep 17 00:00:00 2001 From: dandds Date: Tue, 25 Sep 2018 10:44:19 -0400 Subject: [PATCH] refactor form component validation into class --- js/components/forms/new_project.js | 56 ++++++++++++++++++++---------- 1 file changed, 38 insertions(+), 18 deletions(-) diff --git a/js/components/forms/new_project.js b/js/components/forms/new_project.js index fcab3823..c4aa3642 100644 --- a/js/components/forms/new_project.js +++ b/js/components/forms/new_project.js @@ -9,6 +9,39 @@ const VALIDATIONS = { showEmptyError: "environmentsHaveNames", } +class Validator { + constructor(validations) { + this.validations = validations + } + + errorList() { + let errors = {} + this.map((key) => { + errors[key] = false + }) + return errors + } + + map(callback) { + Object.keys(this.validations).map((k) => callback(k)) + } + + update(object) { + this.map((errName) => { + if (object[this.validations[errName]]()) { + object.errors[errName] = false + } + }) + } + + validate(object) { + this.map((errName) => { + object.errors[errName] = !object[this.validations[errName]]() + }) + return Object.values(object.errors).every(e => e) + } +} + export default { name: 'new-project', @@ -37,13 +70,11 @@ export default { : [""] ).map(createEnvironment) - let errors = {} - Object.keys(VALIDATIONS).map((key) => { - errors[key] = false - }) + const validator = new Validator(VALIDATIONS) return { - errors, + validator, + errors: validator.errorList(), environments, name, } @@ -54,12 +85,7 @@ export default { }, updated: function() { - Object.keys(VALIDATIONS).map((errName) => { - const func = VALIDATIONS[errName] - if (this[func]()) { - this.errors[errName] = false - } - }) + this.validator.update(this) }, methods: { @@ -102,13 +128,7 @@ export default { return newVal.showValid && previous }, true) - Object.keys(VALIDATIONS).map((errName) => { - const func = VALIDATIONS[errName] - if (!this[func]()) { - isValid = false - this.errors[errName] = true - } - }) + isValid = this.validator.validate(this) && isValid if (isValid) { this.openModal(modalName)