boss-validator
Version:
The simplest library to validate data or forms.
1 lines • 11.4 kB
JavaScript
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define("Boss",[],t):"object"==typeof exports?exports.Boss=t():e.Boss=t()}("undefined"!=typeof self?self:this,function(){return function(e){function t(n){if(r[n])return r[n].exports;var a=r[n]={i:n,l:!1,exports:{}};return e[n].call(a.exports,a,a.exports,t),a.l=!0,a.exports}var r={};return t.m=e,t.c=r,t.d=function(e,r,n){t.o(e,r)||Object.defineProperty(e,r,{configurable:!1,enumerable:!0,get:n})},t.n=function(e){var r=e&&e.__esModule?function(){return e.default}:function(){return e};return t.d(r,"a",r),r},t.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},t.p="",t(t.s=0)}([function(e,t,r){"use strict";var n=r(1),a=r(2),o=r(4),s=r(5),l={_errorClassInput:"boss--is-wrong",_errorClassSpan:"boss--error",errors:[],options:{appendErrors:!0,errorElement:"label"},validators:n,messages:a,configure:function(e){this.options=Object.assign({},this.options,e)},configureMessages:function(e){try{if("object"!==this._typeof(e))throw new Error("configureMessages: Please, your messages needs to be an object of keys and values (string).");this.messages=Object.assign({},this.messages,e)}catch(e){console.error(e.getMessage())}},loadLanguage:function(e){return this.configureMessages(e)},addValidator:function(e){if("object"!==this._typeof(e))throw new TypeError("addValidator: The param needs to be an object.");if(!("name"in e||"validator"in e))throw new TypeError("addValidator: You need to pass a name and a validator function.");if("string"!==this._typeof(e.name))throw new TypeError("addValidator: The name property needs to be a string.");if("function"!==this._typeof(e.validator))throw new TypeError("addValidator: The validator property needs to be a function");this.validators[e.name]=e.validator.bind(this),this.messages[e.name]=e.message||!1},validate:function(e,t,r){var n=this,o=Object.keys(t);n.data=e,n.errors=[];for(var s=0,l=o.length;s<l;s++){var i=o[s],u=e[i],c=n._typeof(u);if(void 0!==u&&("string"===c||"object"===c||"htmlinputelement"===c)){var f=t[i],p=Object.keys(f);"string"===c&&-1===c.indexOf("html")&&(u={value:u});for(var d=0,h=p.length;d<h;d++){var v=p[d],g=n.validators[v],m=f[v],b=n.messages[v],y=void 0;if("object"===n._typeof(m)&&(b=m.message,m=m.value),"between"==v){for(var _="",w=0,x=m.length;w<x;++w)_+=m[w].join(a.prepositions.and),w!=x-1&&(_+=a.prepositions.or);y=_}"undefined"!==n._typeof(g)?g.call(n,u,m,f)||n.errors.push({el:u,data:u.value,rule:v,value:m,name:i,message:n._supplant(b||n.messages.default,{val:y||m.toString()})}):n.errors.push({rule:v,value:m,message:'The validator "'+v+"\" doesn't exist. Please check its name."})}}}return"htmlformelement"===n._typeof(e)&&n.options.appendErrors&&n.errors.length&&n._appendErrors(),n.errors.length?Promise.reject(n.errors):"object"===n._typeof(r)?Promise.resolve({transformed:n._filter(e,r),source:e}):Promise.resolve({source:e})},setErrorClass:function(e){this._errorClassSpan=e+" boss--error"},transform:function(e,t){return this._filter(e,t)},_filter:function(e,t){var r=this,n=r._typeof(e),a=r._typeof(t),l=Object.keys(t),i={};if("htmlformelement"!==n&&"object"!==n)throw new Error("filter: Only HTML form element or object are allowed.");if("object"!==a)throw new Error("filter: The filter param must be an object.");"htmlformelement"===n&&(e=s(e,{hash:!0,empty:!0}));for(var u=0,c=l.length;u<c;u++)!function(n,a){var s=l[n],u=e[s];if(s in e){t[s].forEach(function(e){"string"!==r._typeof(u)&&"value"in u?o[e]&&(u.value=o[e](u.value)):o[e]&&(u=o[e](u))}),i[s]=u}}(u);return Object.assign({},e,i)},_clearErrors:function(){var e=this,t=document.querySelectorAll(".boss--error"),r=document.querySelectorAll(".boss--is-wrong");r&&[].forEach.call(r,function(t){t.classList.remove(e._errorClassInput.split(" "))}),t&&[].forEach.call(t,function(t){e._removeNode(t)})},_appendErrors:function(){var e=this.errors;this._clearErrors();for(var t=0,r=e.length;t<r;++t)this._appendError(e[t])},_insertAfter:function(e,t){t.parentNode.insertBefore(e,t.nextSibling)},_removeNode:function(e){e.parentElement.removeChild(e)},_appendError:function(e){var t=document.createElement(this.options.errorElement||"label");t.innerHTML=this._supplant(e.message,{val:e.value.toString()}),t.htmlFor=e.el.id||null,t.className=this._errorClassSpan+" boss--error-"+e.rule,e.el.classList.add(this._errorClassInput),this._insertAfter(t,e.el)},_supplant:function(e,t){return e.replace(/{([^{}]*)}/g,function(e,r){var n=t[r];return"string"==typeof n||"number"==typeof n?n:e})},_typeof:function(e){return Object.prototype.toString.call(e).replace(/(\[|\])/g,"").split(" ")[1].toLowerCase()}};e.exports=l},function(e,t,r){"use strict";var n={required:function(e){return"type"in e&&("checkbox"===e.type||"radio"===e.type)?e.checked:"string"==typeof e.value&&!!e.value.length},number:function(e){return e.value.match(/^[0-9]+$/g)},less:function(e,t){return!!parseFloat(e.value)&&parseFloat(e.value)<t},bigger:function(e,t){return!!parseFloat(e.value)&&parseFloat(e.value)>t},less_equal:function(e,t){return!!parseFloat(e.value)&&parseFloat(e.value)<=t},bigger_equal:function(e,t){return!!parseFloat(e.value)&&parseFloat(e.value)>=t},between:function(e,t){if("array"===this._typeof(t)){for(var r=t.length,n=parseFloat(e.value),a=0,o=r;a<o;++a){var s=t[a],l=s[0],i=s[1];if(n>=l&&n<=i)return!0}return!1}throw new Error('"between" validator needs an array of at least one array of two values.')},exact:function(e,t){return"string"==typeof e.value&&e.value.length==t},minlength:function(e,t){return"string"==typeof e.value&&e.value.length>=t},maxlength:function(e,t){return"string"==typeof e.value&&e.value.length<=t},extensions:function(e,t){for(var r=0,n=t.length;r<n;++r){var a=t[r];if(-1!==e.value.indexOf("."+a))return!0}},starts:function(e,t){return 0===e.value.indexOf(t)},ends:function(e,t){return e.value.endsWith(t)},contains:function(e,t){return e.value.indexOf(t)>=0},boolean:function(e){var t=String(e.value);return"true"===t||"false"===t},email:function(e){var t=/^[A-Za-z0-9](([_\.\-]?[a-zA-Z0-9]+)*)@([A-Za-z0-9]+)(([\.\-]?[a-zA-Z0-9]+)*)\.([A-Za-z]{2,})$/;return null!==e.value.match(t)},regex:function(e,t){return null!==e.value.match(t)},url:function(e,t){var r=/^((((https?|ftps?|gopher|telnet|nntp):\/\/)|(mailto:|news:))(%[0-9A-Fa-f]{2}|[-()_.!~*';\/?:@&=+$,A-Za-z0-9])+)([).!';\/?:,][[:blank:]])?$/;return null!==e.value.match(r)},https:function(e,t){var r=t?/^https/:/^(?!https)/;return null!==e.value.match(r)},credit_card:function(e){var t=String(e.value),r=void 0,n=void 0,a=void 0,o=void 0;for(a=+t[r=t.length-1],o=0;r--;)n=+t[r],a+=++o%2?2*n%10+(n>4):n;return a%10==0},ip_v4:function(e){var t=/^(?:(?:1\d{0,2}|[3-9]\d?|2(?:[0-5]{1,2}|\d)?|0)\.){3}(?:1\d{0,2}|[3-9]\d?|2(?:[0-5]{1,2}|\d)?|0)$/;return null!==e.value.match(t)},ip_v6:function(e){var t=/^([0-9A-Fa-f]{1,4}:){7}[0-9A-Fa-f]{1,4}$/;return null!==e.value.match(t)},alpha_numeric:function(e){var t=/^[a-zA-Z0-9]+$/;return null!==e.value.match(t)},alpha:function(e){var t=/^[a-zA-Z]+$/;return null!==e.value.match(t)}};e.exports=n},function(e,t,r){"use strict";e.exports=r(3)},function(e,t,r){"use strict";var n={default:"Please fill in this field.",required:"This field is required.",prepositions:{and:" and ",or:" or "},less:"The value needs to be less than {val}.",less_equal:"The value needs to be less than or equal to {val}.",bigger:"The value needs to be bigger than {val}.",bigger_equal:"The value needs to be less than or equal to {val}.",between:"The value must be between {val}",number:"Please enter a valid number.",exact:"Must contain the following characters: {val}",extensions:"Please upload a file with the following extensions: {val}.",contains:"Must contain the following value: {val}.",minlength:"Must be at least {val} characters long.",maxlength:"Must be less than {val} characters long.",starts:'This field should start with "{val}".',ends:'This field should end with "{val}".',boolean:'This field needs to be "true" or "false".',email:"Please provide a valid email address. (ex: user@gmail.com)",url:"Please provide a valid URL address with http:// or https://",https:"Your URL must start with https://",credit_card:"Please enter a valid credit card number.",ip_v4:"Please enter a valid IPV4 address. (ex: 172.16.254.1)",ip_v6:"Please enter a valid IPV6 address. (ex: 3ffe:1900:4545:3:200:f8ff:fe21:67cf)",alpha:"Only letters are allowed.",alpha_numeric:"No special characters allowed, just numbers and letters."};e.exports=n},function(e,t,r){"use strict";var n={trim:function(e){return"string"==typeof e?e.trim():e},uppercase:function(e){return"string"==typeof e?e.toUpperCase():e},lowercase:function(e){return"string"==typeof e?e.toLowerCase():e},base64_encode:function(e){return btoa(e)},base64_decode:function(e){return"string"==typeof e?atob(e):e},urlencode:function(e){return encodeURI(e)},urldecode:function(e){return decodeURI(e)},json_parse:function(e){return JSON.parse(e)},json_decode:function(e){return JSON.stringify(e)},slug:function(e){for(var t=e.toString().toLowerCase().trim().replace(/\s+/g,"-").replace(/&/g,"-and-").replace(/\-\-+/g,"-").replace(/^-+/,"").replace(/-+$/,""),r="àáäâèéëêìíïîòóöôùúüûñç·/_,:;",n="aaaaeeeeiiiioooouuuunc------",a=0,o=r.length;a<o;a++)t=t.replace(new RegExp(r.charAt(a),"g"),n.charAt(a));return t},html_escape:function(e){return e.replace(/&/g,"&").replace(/"/g,""").replace(/'/g,"'").replace(/</g,"<").replace(/>/g,">")},html_unescape:function(e){return e.replace(/"/g,'"').replace(/'/g,"'").replace(/</g,"<").replace(/>/g,">").replace(/&/g,"&")}};e.exports=n},function(e,t){function r(e,t){"object"!=typeof t?t={hash:!!t}:void 0===t.hash&&(t.hash=!0);for(var r=t.hash?{}:"",n=t.serializer||(t.hash?o:s),a=e&&e.elements?e.elements:[],u=Object.create(null),c=0;c<a.length;++c){var f=a[c];if((t.disabled||!f.disabled)&&f.name&&(i.test(f.nodeName)&&!l.test(f.type))){var p=f.name,d=f.value;if("checkbox"!==f.type&&"radio"!==f.type||f.checked||(d=void 0),t.empty){if("checkbox"!==f.type||f.checked||(d=""),"radio"===f.type&&(u[f.name]||f.checked?f.checked&&(u[f.name]=!0):u[f.name]=!1),void 0==d&&"radio"==f.type)continue}else if(!d)continue;if("select-multiple"!==f.type)r=n(r,p,d);else{d=[];for(var h=f.options,v=!1,g=0;g<h.length;++g){var m=h[g],b=t.empty&&!m.value,y=m.value||b;m.selected&&y&&(v=!0,r=t.hash&&"[]"!==p.slice(p.length-2)?n(r,p+"[]",m.value):n(r,p,m.value))}!v&&t.empty&&(r=n(r,p,""))}}}if(t.empty)for(var p in u)u[p]||(r=n(r,p,""));return r}function n(e){var t=[],r=/^([^\[\]]*)/,n=new RegExp(u),a=r.exec(e);for(a[1]&&t.push(a[1]);null!==(a=n.exec(e));)t.push(a[1]);return t}function a(e,t,r){if(0===t.length)return e=r;var n=t.shift(),o=n.match(/^\[(.+?)\]$/);if("[]"===n)return e=e||[],Array.isArray(e)?e.push(a(null,t,r)):(e._values=e._values||[],e._values.push(a(null,t,r))),e;if(o){var s=o[1],l=+s;isNaN(l)?(e=e||{},e[s]=a(e[s],t,r)):(e=e||[],e[l]=a(e[l],t,r))}else e[n]=a(e[n],t,r);return e}function o(e,t,r){if(t.match(u))a(e,n(t),r);else{var o=e[t];o?(Array.isArray(o)||(e[t]=[o]),e[t].push(r)):e[t]=r}return e}function s(e,t,r){return r=r.replace(/(\r)?\n/g,"\r\n"),r=encodeURIComponent(r),r=r.replace(/%20/g,"+"),e+(e?"&":"")+encodeURIComponent(t)+"="+r}var l=/^(?:submit|button|image|reset|file)$/i,i=/^(?:input|select|textarea|keygen)/i,u=/(\[[^\[\]]*\])/g;e.exports=r}])});