Last active
August 7, 2019 14:43
-
-
Save phatnguyenuit/8ef2bdeabca1fc8eedc1fd9196d9f9a7 to your computer and use it in GitHub Desktop.
Multiple validation conditions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| const isTruthy = param => !!param; | |
| const isString = param => typeof (param) === 'string'; | |
| const isNumeric = param => /^\d+$/.test(param); | |
| const makeConditionalMethod = (method, required = false) => (...params) => { | |
| const res = method(...params); | |
| const valid = isTruthy(...params); | |
| if (required) { | |
| return valid && res; | |
| } | |
| return valid ? res : true; | |
| } | |
| const isStringRequired = makeConditionalMethod(isString, true); | |
| const isNumericRequired = makeConditionalMethod(isNumeric, true); | |
| const fieldValidation = { | |
| "field1": isStringRequired, | |
| "field2": [isNumericRequired], | |
| } | |
| const data = { | |
| field1: "123", | |
| field2: "ahihi", | |
| } | |
| for (const key in data) { | |
| if (fieldValidation.hasOwnProperty(key)) { | |
| let funcs = fieldValidation[key]; | |
| if (typeof (funcs) === 'function') { | |
| funcs = [funcs]; | |
| } | |
| const result = funcs.map(func => func(...data[key])); | |
| console.log(result.every(Boolean)) | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment