Last active
March 29, 2018 22:41
-
-
Save js2me/36a3b5bce7651cdcc6a6a2435852109e to your computer and use it in GitHub Desktop.
NICE STRING VALIDATOR
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 _validators = { | |
required: value => !!value.length, | |
'min-length': (value, min) => value.length >= +min, | |
'max-length': (value, max) => value.length <= +max, | |
number: value => isNaN(+value), | |
equals: (value, equals) => value === equals, | |
regexp: (value, regexp) => new RegExp(regexp).test(value), | |
} | |
/** | |
* Validate string using validators parameter (validators can consist of 'required', 'min-length', 'max-length', 'number') | |
* @param {string} field | |
* @param {string[]} validators its array of strings. strings : 'required' 'min-length#{number}' 'max-length#{number}' 'number' | |
* @returns {boolean} true/false validation result | |
* @example | |
* // returns true | |
* validateString('example1', ['required','min-length#5']); | |
* @example | |
* // returns false | |
* validateString('example2', ['required','number']); | |
*/ | |
export const validateString = (field, validators) => | |
validators | |
.map(v => { | |
const split = v.split('#') | |
return _validators[split[0]] && _validators[split[0]](field, split[1]) | |
}) | |
.every(v => !!v) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
perf tests:
https://jsperf.com/check-string-validation-classic-array-2 (classic array)
https://jsperf.com/check-string-validation/1 (map and every methods)