Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // NOTE: how to use
- // how to get a validator function that checks if a string has a minimum length of 4
- // let minimumLength = 4;
- // let hasMinimumLengthOfFour = hashmapOfValidatorFunctionsToBeCurried['min_length'](minimumLength);
- // hasMinimumLengthOfFour('un') -> return false
- // hasMinimumLengthOfFour('quatre') -> return true
- // NOTE2: the keys has to be in sync with what the private api's delivers
- // in the validation_rules key
- const hashmapOfValidatorFunctionsToBeCurried = Object.freeze({
- min_length: (limit) => (string = '') => string.length >= limit,
- max_length: (limit) => (string = '') => string.length <= limit,
- required: (boolean) => (value) => boolean === false ? true : !!value,
- });
- /**
- * [_getValidatorFunctionForValidationRules this function is used to return a validator function that
- * will apply all the validation rules onto the desired value and return true
- * if all the validation rules are respected]
- * @param {[Object]} validationRules [object containing all the validation
- * rules and their limits (e.g. = {min_length: 10})]
- * @return {[Function]} [A validator function that accept the value to be checked
- * as its argument it will then run all of the validator functions onto the
- * desired value and returns true if all test have passed]
- */
- function getValidatorFunctionForValidationRules(validationRules) {
- let validationRulesFunctions = {};
- if (!validationRules) return null;
- Object.keys(validationRules).map(rule => {
- let ruleValue = validationRules[rule];
- if (!hashmapOfValidatorFunctionsToBeCurried[rule]) return;
- let validationFunction = hashmapOfValidatorFunctionsToBeCurried[rule](ruleValue);
- validationRulesFunctions[rule] = validationFunction;
- });
- let validationFunctionsCount = Object.keys(validationRulesFunctions).length;
- if (validationFunctionsCount > 0) {
- return function(value) {
- let reducer = (is_valid, function_key) => {
- return is_valid && validationRulesFunctions[function_key](value);
- }
- // note: we set the start value at true in order to properly evaluate the
- // first rule. if we started with false and the first value was indeed valid then
- // it will return false for the first iteration which is bad and not true.
- // also note that the use of the && operator is mandatory since we want to verify
- // that **all rules** are respected.
- return Object.keys(validationRulesFunctions).reduce(reducer, true);
- };
- } else {
- return null;
- }
- }
- export { getValidatorFunctionForValidationRules, hashmapOfValidatorFunctionsToBeCurried }
Add Comment
Please, Sign In to add comment