UNPKG

@shopgate/engage

Version:
12 lines 2.07 kB
function _defineProperty(obj,key,value){if(key in obj){Object.defineProperty(obj,key,{value:value,enumerable:true,configurable:true,writable:true});}else{obj[key]=value;}return obj;}function _extends(){_extends=Object.assign||function(target){for(var i=1;i<arguments.length;i++){var source=arguments[i];for(var key in source){if(Object.prototype.hasOwnProperty.call(source,key)){target[key]=source[key];}}}return target;};return _extends.apply(this,arguments);}import moment from'moment';import validateJs from'validate.js';validateJs.options={format:'detailed',fullMessages:false};validateJs.extend(validateJs.validators.datetime,{// The value is guaranteed not to be null or undefined but otherwise it // could be anything. parse:function parse(value){return+moment.utc(value);},// Input is a unix timestamp format:function format(value,options){var format=options.dateOnly?'YYYY-MM-DD':'YYYY-MM-DD hh:mm:ss';return moment.utc(value).format(format);}});/** * @param {Object} values The values to validate. * @param {Object} constraints The constraints. * @returns {{ valid: boolean, validationErrors: Object }} */export function validate(values,constraints){var sanitizedValues=_extends({},values);/** * When the presence constrain is not set, empty strings are considered as not empty and those * values will be passed through other validators like datetime, where they can cause false * negatives. So we'll just convert them to null for the validator. */Object.keys(sanitizedValues).forEach(function(key){var value=sanitizedValues[key];if(value===''){sanitizedValues[key]=null;}});var errors=validateJs(sanitizedValues,constraints);if(errors&&Object.keys(errors).length>0){errors=errors.reduce(function(obj,item){var _item$options;if(obj[item.attribute]){return obj;}return _extends({},obj,_defineProperty({},item.attribute,(item===null||item===void 0?void 0:(_item$options=item.options)===null||_item$options===void 0?void 0:_item$options.message)||(item===null||item===void 0?void 0:item.error)));},{});}return{valid:!errors,validationErrors:errors};}