UNPKG

@rootstrap/validate

Version:

An extension of validate.js with useful and common custom validations

63 lines (51 loc) 1.76 kB
'use strict'; var validate = require('validate.js'); var get = require('lodash/get'); function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } var validate__default = /*#__PURE__*/_interopDefaultLegacy(validate); var get__default = /*#__PURE__*/_interopDefaultLegacy(get); const noPresence = (value, { includeFalse = false }) => { const isNotPresent = validate__default['default'].single(value, { presence: true, }); if (!isNotPresent || (value === false && !includeFalse)) { return 'ERRORS.noPresence'; } }; const conditionalConstraints = ( value, { dependencies, constraints }, key, attributes, ) => { let validDependencies = true; dependencies.forEach( ({ attribute: name, constraints: dependencyConstraints }) => { const errors = validate__default['default'].single( get__default['default'](attributes, name), dependencyConstraints, ); validDependencies = validDependencies && !errors; }, ); if (validDependencies) { const errors = validate__default['default']( attributes, { [key]: constraints }, { fullMessages: false }, ); if (errors) { return errors[key]; } } }; /* Overrides allowEmpty for presence default because it makes no sense Should you need to set it back to the default you can simply override it the same way it is overwritten here. */ validate__default['default'].validators.presence.options = { allowEmpty: false }; // CUSTOM, BUT COMMON, VALIDATORS validate__default['default'].validators.noPresence = noPresence; validate__default['default'].validators.conditionalConstraints = conditionalConstraints; module.exports = validate__default['default'];