Skip to content

Instantly share code, notes, and snippets.

@phatnguyenuit
Last active August 7, 2019 14:43
Show Gist options
  • Select an option

  • Save phatnguyenuit/8ef2bdeabca1fc8eedc1fd9196d9f9a7 to your computer and use it in GitHub Desktop.

Select an option

Save phatnguyenuit/8ef2bdeabca1fc8eedc1fd9196d9f9a7 to your computer and use it in GitHub Desktop.
Multiple validation conditions
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