import {validator} from 'vendor'; export function validateAll(value, validations) { for(let conf of validations) validate(value, conf); } export function validate(value, conf) { let validator = validators[conf.validation]; try { checkNull(value, conf); validator && validator(value, conf); } catch(e) { let message = conf.message ? conf.message : e.message; throw new Error(message); } } export function checkNull(value, conf) { if (typeof value === 'undefined') { if (!conf.allowBlank) throw new Error(`Value can't be blank`); } else { if (value === null && !conf.allowNull) throw new Error(`Value can't be null`); } } export const validators = { presence: function(value, conf) { if(validator.isEmpty(value)) throw new Error(`Value can't be empty`); }, absence: function() { if(!validator.isEmpty(value)) throw new Error(`Value should be empty`); }, length: function(value, conf) { let options = { min: conf.min || conf.is, max: conf.max || conf.is }; if(!validator.isLength(value, options)) { if(conf.is) throw new Error(`Value should be ${conf.is} characters long`); else throw new Error(`Value should have a length between ${conf.min} and ${conf.max}`); } }, numericality: function(value, conf) { if(conf.int) { if(!validator.isInt(value)) throw new Error(`Value should be integer`); } else { if(!validator.isNumeric(vlaue)) throw new Error(`Value should be a number`); } }, inclusion: function(value, conf) { if(!validator.isIn(value, conf.in)) throw new Error(`Invalid value`); }, exclusion: function(value, conf) { if(validator.isIn(value, conf.in)) throw new Error(`Invalid value`); }, format: function(value, conf) { if(!validator.matches(value, conf.with)) throw new Error(`Invalid value`); }, custom: function(value, conf) { let valid = true; function err(kind) { valid = false; } let inst = {attr: value}; conf.customValidator.call(inst, err) if(!valid) throw new Error(`Invalid value`); }, uniqueness: function() { // TODO: Implement me }, };