UNPKG

@chrisbrocklesby/validation

Version:

This is a validation helper, It helps validate JSON data via a quick rule set you create.

60 lines (49 loc) 1.36 kB
module.exports = { validate(rules) { const errors = rules.reduce((errs, rule) => { if (rule.isValid === false) { errs.push(rule.message || null); } return errs; }, []); class ValidationError { constructor(message) { this.name = 'validationError'; this.messages = (message || null); } } if (errors.length) { throw new ValidationError(errors); } }, isString(data) { return (data) ? !!(typeof data === 'string') : true; }, isNumber(data) { return (data) ? !!(typeof data === 'number') : true; }, isBoolean(data) { return (data) ? !!(typeof data === 'boolean') : true; }, isArray(data) { return (data) ? !!(!!data && data.constructor === Array) : true; }, isObject(data) { return (data) ? !!(typeof data === 'object') : true; }, isRequired(data) { return !(typeof data === 'undefined' || ''); }, notNull(data) { return (data) ? !!(data !== null) : true; }, isPk(data) { return (data) ? /^[0-9a-f]{8}-[0-9a-f]{4}-[0-5][0-9a-f]{3}-[089ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(data) : true; }, isEmail(data) { return (data) ? /^\w+([.-]?\w+)*@\w+([.-]?\w+)*(\.\w{2,3})+$/.test(data) : true; }, isPassword(data) { return (data) ? /^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.{8,})/.test(data) : true; }, };