@flatfile/plugin-validate-number
Version:
A Flatfile Listener plugin for number validation
11 lines (8 loc) • 2.1 kB
JavaScript
;
var pluginRecordHook = require('@flatfile/plugin-record-hook');
function l(s,e){let t={value:null,errors:[],warnings:[]};try{let r=String(s).replace(e.thousandsSeparator||",","").replace(e.decimalPoint||".",".");if(r=parseFloat(r),isNaN(r))return t.errors.push("Must be a number"),t;if(e.round&&(r=Math.round(r)),e.truncate&&(r=Math.trunc(r)),e.integerOnly&&!Number.isInteger(r)&&t.warnings.push("Must be an integer"),e.min!==void 0&&(e.inclusive?r<e.min:r<=e.min)&&t.warnings.push(`Must be greater than ${e.inclusive?"or equal to ":""}${e.min}`),e.max!==void 0&&(e.inclusive?r>e.max:r>=e.max)&&t.warnings.push(`Must be less than ${e.inclusive?"or equal to ":""}${e.max}`),e.precision!==void 0&&e.scale!==void 0){let[a,n]=r.toString().split(".");a.length>e.precision-e.scale&&t.warnings.push(`Must have at most ${e.precision-e.scale} digits before the decimal point`),n&&n.length>e.scale&&t.warnings.push(`Must have at most ${e.scale} digits after the decimal point`);}e.currency&&!/^\d+(\.\d{1,2})?$/.test(r.toString())&&t.warnings.push("Must be a valid currency value with at most two decimal places"),e.step!==void 0&&r%e.step!==0&&t.warnings.push(`Must be a multiple of ${e.step}`),e.specialTypes&&(e.specialTypes.includes("prime")&&!p(r)&&t.warnings.push("Must be a prime number"),e.specialTypes.includes("even")&&r%2!==0&&t.warnings.push("Must be an even number"),e.specialTypes.includes("odd")&&r%2===0&&t.warnings.push("Must be an odd number")),t.value=r;}catch(r){t.errors.push(`Error processing value: ${r.message}`);}return t}function d(s){return e=>{e.use(pluginRecordHook.recordHook(s.sheetSlug||"**",async t=>{for(let r of s.fields){let a=t.get(r);if(typeof a!="string"&&typeof a!="number")return t;let n=l(a,s);n.value!==null&&t.set(r,n.value),n.errors.forEach(i=>t.addError(r,i)),n.warnings.forEach(i=>t.addWarning(r,i));}return t}));}}function p(s){for(let e=2,t=Math.sqrt(s);e<=t;e++)if(s%e===0)return !1;return s>1}
exports.isPrime = p;
exports.validateNumber = d;
exports.validateNumberField = l;
//# sourceMappingURL=index.cjs.map
//# sourceMappingURL=index.cjs.map