Skip to content

Instantly share code, notes, and snippets.

@js2me
Last active March 29, 2018 22:41
Show Gist options
  • Save js2me/36a3b5bce7651cdcc6a6a2435852109e to your computer and use it in GitHub Desktop.
Save js2me/36a3b5bce7651cdcc6a6a2435852109e to your computer and use it in GitHub Desktop.
NICE STRING VALIDATOR
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)
@js2me
Copy link
Author

js2me commented Mar 29, 2018

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment