import {validator} from 'vendor'; export const validators = { presence: value => { if (validator.isEmpty(value.toString())) throw new Error(`Value can't be empty`); }, absence: value => { if (!validator.isEmpty(value)) throw new Error(`Value should be empty`); }, length: (value, conf) => { let options = { min: conf.min || conf.is, max: conf.max || conf.is }; let val = value ? String(value) : ''; if (!validator.isLength(val, options)) { if (conf.is) { throw new Error(`Value should be ${conf.is} characters long`); } else if (conf.min && conf.max) { throw new Error(`Value should have a length between ${conf.min} and ${conf.max}`); } else if (conf.min) { throw new Error(`Value should have at least ${conf.min} characters`); } else { throw new Error(`Value should have at most ${conf.max} characters`); } } }, numericality: (value, conf) => { if (conf.int) { if (!validator.isInt(value)) throw new Error(`Value should be integer`); } else if (!validator.isNumeric(value)) throw new Error(`Value should be a number`); }, inclusion: (value, conf) => { if (!validator.isIn(value, conf.in)) throw new Error(`Invalid value`); }, exclusion: (value, conf) => { if (validator.isIn(value, conf.in)) throw new Error(`Invalid value`); }, format: (value, conf) => { if (!validator.matches(value, conf.with)) throw new Error(`Invalid value`); }, custom: (value, conf) => { if (!conf.bindedFunction(value)) throw new Error(`Invalid value`); } }; /** * Checks if value satisfies a set of validations. * * @param {*} value The value * @param {Array} validations Array with validations */ export function validateAll(value, validations) { for (let conf of validations) validate(value, conf); } /** * Checks if value satisfies a validation. * * @param {*} value The value * @param {Object} conf The validation configuration */ export function validate(value, conf) { let validator = validators[conf.validation]; try { checkNull(value, conf); if (validator) // && value != null ?? validator(value, conf); } catch (e) { let message = conf.message ? conf.message : e.message; throw new Error(message); } } /** * Checks if value satisfies a blank or not null validation. * * @param {*} value The value * @param {Object} conf The validation configuration */ export function checkNull(value, conf) { if (conf.allowBlank === false && value === '') throw new Error(`Value can't be blank`); else if (conf.allowNull === false && value == null) throw new Error(`Value can't be null`); }