validlyjs
Version:
A high-performance Laravel-inspired validation library for TypeScript/JavaScript
18 lines (17 loc) • 1.41 kB
JavaScript
function e(e){if("number"==typeof e){if(isNaN(e)||0>e)throw Error("Invalid size: must be a non-negative number")
return e}if("string"!=typeof e)throw Error("Invalid size: must be a number or string")
const t=e.match(/^(\d*\.?\d+)\s*(B|KB|MB|GB|TB)$/i)
if(!t)throw Error("Invalid size format: "+e)
const r=parseFloat(t[1]),i=t[2].toUpperCase(),n={B:1,KB:1024,MB:1048576,GB:1073741824,TB:1099511627776}
if(isNaN(r)||0>r)throw Error("Invalid size: value must be a non-negative number")
if(!n[i])throw Error("Invalid size unit: "+i)
return r*n[i]}const t={name:"file.min",validate:(t,r)=>{if(!t||"object"!=typeof t||!("size"in t))return!1
const i=t,[n]=r,a=e(n)
return i.size>=a},message:"The {field} must be at least {0}.",priority:2},r={name:"file.max",validate:(t,r)=>{if(!t||"object"!=typeof t||!("size"in t))return!1
const i=t,[n]=r
return e(n)>=i.size},message:"The {field} may not be greater than {0}.",priority:2},i={name:"file.size",validate:(t,r)=>{if(!t||"object"!=typeof t||!("size"in t))return!1
const i=t,[n]=r,a=e(n)
return i.size==a},message:"The {field} size must be greater than {0}.",priority:2},n={name:"file.between",validate:(t,r)=>{if(!t||"object"!=typeof t||!("size"in t))return!1
const i=t,[n,a]=r,s=e(n),o=e(a)
return i.size>=s&&o>=i.size},message:"The {field} size must be between {0} and {1}.",priority:2}
export{r as fileMaxRule,t as fileMinRule,n as fileRangeRule,i as fileSizeRule}